snickinicki
snickinicki

Reputation: 3

Append new list every iteration of the for loop

I want to somehow append to a new list every time I enter a for loop. Currently I have:

A=[ ] 
B = [ ]
C = [ ]

For i in range (1, 4):
   if i == 1:
        A.append(x)
   if i == 2:
        B.append(x)
   ...

and so on. I am looking for an easier way to do this, as it feels so hard-coded.

Upvotes: 0

Views: 1121

Answers (1)

fredtantini
fredtantini

Reputation: 16556

You could simply use a list of lists:

>>> A=[ ]
>>> B = [ ]
>>> C = [ ]
>>> allLists =[A,B,C]
>>> X=range(10,20)
>>> for i,j in enumerate(X):
...   allLists[i%len(allLists)].append(j)
...
>>> A,B,C
([10, 13, 16, 19], [11, 14, 17], [12, 15, 18])

Another way is to use slicing:

>>> def chunk(l,n):
...  result=[]
...  for i in range(n):
...    result.append(l[i::n])
...  return result
...
>>> A,B,C=chunk(X,3)
>>> A,B,C
([10, 13, 16, 19], [11, 14, 17], [12, 15, 18])
>>> A,B,C,D=chunk(X,4)
>>> A,B,C,D
([10, 14, 18], [11, 15, 19], [12, 16], [13, 17])

Upvotes: 1

Related Questions