1

How do I loop over a range of integers, concatenating a string, such as "array" with the iterate of the loop, and initialize a list with the resulting string? The following single line shows what I want to do, where I get a "can't assign to function call" error.

for i in range(int(nmat)): eval('array'+str(i)) = []

Meanwhile, further down in the code the following code is accepted (provided I comment out the preceding code that caused it to bomb)

eval('array'+str(ct1)).append(array[1:9])

However it tells me that the name 'array0' is undefined (since I don't know how to initialize a series of lists in this manner). Help would be greatly appreciated, thanks.

2 Answers 2

5

You shouldn't do that.

Instead of having numerous variables arrayi, use just one: array, of type list. For example, if every element of the list should be an empty list:

array = [[] for i in range(int(nmat))]

You can then access the first element with array[0], the second with array[1], and the number of elements in array (int(nmat) in this case) with len(array).

Sign up to request clarification or add additional context in comments.

5 Comments

Haha, so essentially python's keeping me from being an idiot. What you said makes more sense anyway ... once my mind was stuck on that way to do it I couldn't think outside the box. Thanks.
array = [] * range(3) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'list'
@joaquin Oops, that line was indeed totally messed up. Sorry, corrected now: [[]] * 3. By the way, there is probably no reason to have empty lists laying around either.
Your first line of code is just wrong. By doing array = [[]] * int(nmat) you're creating references to the same empty list.
@Franklin yeah, that will lead to problems down the road. Removed.
4
mylist = []
for i in range(10):
    a = ['array%i' %i]
    mylist.append(a)

print mylist


[['array0'], ['array1'], ['array2'], ['array3'], ['array4'], ['array5'], ['array6'], ['array7'], ['array8'], ['array9']]

in one line:

mylist = [['array%i' %i] for i in range(10)]

You must be very careful with list multiplication:

>> array = [[]] * int('3')
>> array
[[], [], []]
>> array[0] = 'imastring'
>> array
['imastring', [], []]

and still more dangerous:

>> array = [[]] * int('3')
>> array[0].append('repeated')
>> array
[['repeated'], ['repeated'], ['repeated']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.