1

I have a for loop that is taking data and appending it into a list, but for each iteration of the for loop, I would like it to append into a different list. Is there any way to do this?

    value = []
    for i in list:
        value.append(i)

but I would like something such as

    for i, num in enumerate(list):
        value_i.append(num)

How could I go about doing this?

7
  • keep a list of lists. Commented Sep 12, 2013 at 3:00
  • lists = [list1, list2, list3] for i, num in enumerate(list): lists[i].append(num) ? Commented Sep 12, 2013 at 3:01
  • append implies the list already exists. Is that the case? Commented Sep 12, 2013 at 3:08
  • Yes, they already exist. Commented Sep 12, 2013 at 3:31
  • @user2631296 if they already exist, how is sza's answer correct? Commented Sep 12, 2013 at 3:33

4 Answers 4

3
>>> lst = [1,2,3,4]
>>> [list(x) for x in zip(lst)]
[[1], [2], [3], [4]]

Btw, you should not use list as the variable name.

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

Comments

3

Not lists, but close:

>>> zip([1, 2, 5])
[(1,), (2,), (5,)]

Comments

3

Why not simply:

>>> [ [e] for e in [1, 2, 3] ]
[[1], [2], [3]]

Comments

1

Supposing you already have a collection of lists

my_lists = [list1, list2, list3, …, listN]

and a source list

my_sources = [val1, val2, val3, …, valN]

what you want is

for lst, src in zip(my_lists, my_sources):
    lst.append(src)

You could also do this by index:

for i in range(len(lst)):
    my_lists[i].append(my_sources[i])

The latter may seem less Pythonic, but it's pretty readable and probably more efficient than the zip approach.

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.