1

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
7
  • What do you think del a[:] does? Commented Dec 12, 2014 at 20:55
  • del a[:] empties the inner list every time I call the function, so that new set of tuples can be added Commented Dec 12, 2014 at 20:59
  • Yes, it only empties the list. But it's still the same container, each function call is modifying the same object. So, in the end List contains two references to the list a. Simply declare a as a local variable. Commented Dec 12, 2014 at 21:03
  • del a[:] doesn't make any sense. It creates a new copy of the list and then immediately deletes it. Commented Dec 12, 2014 at 21:03
  • 1
    @twasbrillig no, it doesn't. del a[:] simply empties a. It's mutation, not reassignment. Commented Dec 12, 2014 at 21:04

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.