sum2000
sum2000

Reputation: 1403

Unexpected output of python list

I am new to python and I am trying to run following code:

m=int(raw_input())
l=[[0]*2]*m
for i in range(0,m):
    for j in range(0,2):
        l[i][j]=raw_input()
        print l
        print "-------"

Output:

3
1
[['1', 0], ['1', 0], ['1', 0]]
-------
2
[['1', '2'], ['1', '2'], ['1', '2']]
-------
3
[['3', '2'], ['3', '2'], ['3', '2']]
-------
4
[['3', '4'], ['3', '4'], ['3', '4']]
-------
5
[['5', '4'], ['5', '4'], ['5', '4']]
-------
6
[['5', '6'], ['5', '6'], ['5', '6']]

but, when i dry run the program the expected output should be

3
1
[['1', 0], ['1', 0], ['1', 0]]
-------
2
[['1', '2'], ['1', '2'], ['1', '2']]
-------
3
[['1', '2'], ['3', '2'], ['1', '2']]
-------
4
[['1', '2'], ['3', '4'], ['1', '2']]
-------
5
[['1', '2'], ['3', '4'], ['5', '2']
-------
6
[['1', '2'], ['3', '4'], ['5', '6']]

Its like after each iteration list is reassigned, but as I am incrementing 'i' list elements should be like the expected output. Please i need help..

Upvotes: 0

Views: 158

Answers (2)

aquavitae
aquavitae

Reputation: 19154

The problem in the line l=[[0]*2]*m. Doing [[0]] * 3 results in 3 * shallow copies* of the list [0], not three separate lists. A better way of writing your code would be to construct the list as you go. Note that you don't need to specify the start of the range as 0. Also, in python2, xrange is much faster than range, so tis good practice to use it instead.

m=int(raw_input())
l=[]
for i in xrange(m):
    l.append([])
    for j in xrange(2):
        l[i].append(raw_input())
        print l
        print "-------"

You could also do it using a generator and iterating over the list:

m=int(raw_input())
l=[[0, 0] for _ in range(m)]
for sub_list in l:
    for j in xrange(2):
        sub_list[j] = raw_input()
        print l
        print "-------"

Upvotes: 2

kev
kev

Reputation: 161954

s * n, n * s    ==>   n shallow copies of s concatenated 

Note that the copies are shallow; nested structures are not copied.
This often haunts new Python programmers; consider:

>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

You can change your code to:

l = [[0 for i in range(2)] for j in range(m)]

Upvotes: 6

Related Questions