简体   繁体   中英

List of lists in Python -> Getting wrong output

I'm trying to print a list of lists from a loop, but getting the wrong output! The last list that is appended to the bigger list is repeating.

The Output I'm expecting:

FINAL LIST:
[[(1, 2), (2, 3)],
 [(2, 3), (3, 4)]]

The Output I get:

FINAL LIST:
[[(2, 3), (3, 4)],
 [(2, 3), (3, 4)]]

What am I doing wrong here? Here's my code:

a = []
count = 1

#Function that generates some nos. for the list
def func():

    del a[:]
    for i in range(count,count+2):
        x = i
        y = i+1
        a.append((x,y))
    print '\nIn Function:',a    #List seems to be correct here
    return a


#List of lists
List = []
for i in range(1,3):
    b = func()             #Calling Function
    print 'In Loop:',b     #Checking the value, list seems to be correct here also
    List.append(b)
    count = count+1


print '\nList of Lists:'
print List

You're appending the same list ( a ) to List multiple times (which you can see with print List[0] is List[1] ). You need to create multiple lists instead, as in this example:

l = []
for i in xrange(3):
    l.append([i, i+1])
print l

The problem is with the del a[:] statement. The rest of the code is fine. instead of doing that, put an empty a list in the beginning of the function and the problem disappears:

count = 1

#Function that generates some nos. for the list
def func():
    a = []
    for i in range(count,count+2):
        x = i
        y = i+1
        a.append((x,y))
    print '\nIn Function:',a    #List seems to be correct here
    return a


#List of lists
List = []
count = 1
for i in range(1,3):
    b = func()             #Calling Function
    print 'In Loop:',b     #Checking the value, list seems to be correct here also
    List.append(b)
    count = count + 1


print '\nList of Lists:'
print List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM