PKlumpp
PKlumpp

Reputation: 5233

Python list of lists assignment

One thing first: No, this is not a question about why

someThing = [[]] * 10
someThing[0] = 1

gives [1,1,1,1,1,1,1,1,1,1].

My question is a bit more tricky: I do the folling:

x, y, z = ([[]] for i in range(3))

Now I assign a value:

x[0] = 1   # This works fine

And now another one:

x[1] = 2   # This does not work anymore

It gives me an IndexError: list assignment index out of range.

How can I make this work? As you can see, I want an empty list that contains 3 other lists to which i can append values.

Thanks in advance!

Upvotes: 0

Views: 6722

Answers (4)

vapace
vapace

Reputation: 350

Comparing the output of:

for i in [[]] * 3:
    print id(i)

with:

for i in ([[]] for j in range(3)):
    print id(i)

may help answer your finding.

Upvotes: 0

user3233949
user3233949

Reputation: 27

Maybe something like this could work.

lists = [[] for i in range(3)]

The output would be:

[[],[],[]]

If you would like to access/add elements, you could:

lists[0].append(1)
lists[0].append(2)
lists[1].append('a')
lists[1].append('b')

The output would be:

[[1, 2], ['a', 'b'], []]

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

I want an empty list that contains 3 other lists to which i can append values.

Your problem correctly stated is: "I want a list of three empty lists" (something cannot be empty and contain things at the same time).

If you want that, why are you doing it in such a convoluted way? What's wrong with the straightforward approach:

empty_list = [[], [], []]

If you have such a list, when you do empty_list[0] = 1, what you end up with is:

empty_list = [1, [], []]

Instead, you should do empty_list[0].append(1), which will give you:

empty_list = [[1], [], []]

If you want to create an arbitrary number of nested lists:

empty_list = []
for i in range(0, 15):
   empty_list.append([])

Upvotes: 3

freakish
freakish

Reputation: 56467

Since when

someThing = [] * 10
someThing[0] = 1

gives [1,1,1,1,1,1,1,1,1,1]? It's an index error (you can't assign at a nonexisting index), because actually []*10 == []. Your code does exactly the same (I mean an index error). This line

x, y, z = ([[]] for i in range(3))

is short (or not) for

x, y, z = [[]], [[]], [[]]

so x[1] is an index error.

Upvotes: 3

Related Questions