Lists of empty lists in python

I recently needed to create a list of empty lists for a python script. What seemed to me like the most straight forward solution wasn’t actually working as expected.

Normally, when you want to fill a list with something you can just go:

myList = ["hello] * 5
print(myList)

Which would give you:

>>>['hello', 'hello', 'hello', 'hello', 'hello']

So I started with:

myList = [[]] * 5
print(myList)

Which, sure enough, gave me:

>>> [[], [], [], [], []]

However, when I tried to add to one of the empty lists, something unexpected happened:

myList = [[]] * 5
myList[2].append("hello")
print(myList)

What I expected to get was:

>>> [[], [], ['hello'], [], []]

What I actually got was:

>>> [['hello'], ['hello'], ['hello'], ['hello'], ['hello']]

So what’s happening? Well, python is not creating a set of individual empty lists. What it’s creating is 5 references to the same list object. So, all the empty lists stored in myList are all the same instance. When using the syntax myList = [item] * thisMany what you get is thisMany references to the item. You can see this for yourself:

myList = [[]] * 5
for i in myList:
    print(id(i))

The solution, list compresension:

myList = [[] for i in range(5)]

Which appends a new, distinct list to the list its generating with each iteration, and works exactly as expected.

Happy scripting!

Advertisements

~ by Jay on January 8, 2015.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: