3

I'm a Python newbie crossing over from C. I'm basically trying implement logic equivalent to an array of array pointers in C.

I want to append one item to the ends of a bunch of lists by iterating over a list of these lists. I have the following code:

data = [10, 20, 30]
list1 = list2 = list3 = list()
lists = [list1, list2, list3]

for i in range(len(data)):
    lists[i].append(data[i])

for lst in lists:
    print lst

It's result, however, is:

[10, 20, 30]
[10, 20, 30]
[10, 20, 30]

instead of:

[10]
[20]
[30]

I can't explain why this code fails to produce the desired output, and is there some other way of doing this?

mma
  • 119
  • 1
  • 5

1 Answers1

3

You only create one list

list1 = list2 = list3 = list()

this line creates an empty list, assigns its reference to list3, assigns reference to list3 to list2 and to list1, as a result these refer to the same object. So when you add your values, you add them to all of your "lists".

This will work just fine

data = [10, 20, 30]
lists = [[], [], []]

for i in range(len(data)):
    lists[i].append(data[i])

for lst in lists:
    print lst

But the simplest way would be to do just

data = [10, 20, 30]
lists = [ [x] for x in data ]
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
lejlot
  • 64,777
  • 8
  • 131
  • 164
  • The list comprehension is indeed simplest, but it's also notable that we can express the loop as `for i,v in enumerate(data): lists[i].append(v)`, or `for lst,value in zip(lists,data): lst.append(value)`. Needlessly using indices is a bit of a C-ism. – Yann Vernier Sep 21 '13 at 07:39