Python - List of Lists Slicing Behavior

Posted by Dan Dobint on Stack Overflow See other posts from Stack Overflow or by Dan Dobint
Published on 2012-09-17T03:22:25Z Indexed on 2012/09/17 3:37 UTC
Read the original article Hit count: 254

Filed under:
|
|

When I define a list and try to change a single item like this:

list_of_lists = [['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
list_of_lists[1][1] = 'b'
for row in list_of_lists:
    print row

It works as intended. But when I try to use list comprehension to create the list:

row = ['a' for range in xrange(3)]
list_of_lists = [row for range in xrange(3)]
list_of_lists[1][1] = 'b'
for row in list_of_lists:
    print row

It results in an entire column of items in the list being changed. Why is this? How can I achieve the desired effect with list comprehension?

© Stack Overflow or respective owner

Related posts about python

Related posts about list