Running the code
listoflists = []
list = []
for i in range(0,10):
list.append(i)
if len(list)>3:
list.remove(list[0])
listoflists.append((list, list[0]))
print listoflists
returns
[([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 1), ([7, 8, 9], 2), ([7, 8, 9], 3), ([7, 8, 9], 4), ([7, 8, 9], 5), ([7, 8, 9], 6), ([7, 8, 9], 7)]
so somehow the first argument of each tuple (list) is being updated each time in the list of lists, but the second argument list[0] is not. Can someone explain what’s going on here and suggest a way to fix this? I’d like to output
[([0],0), ([0,1],0), ...
Lists are a mutable type – in order to create a copy (rather than just passing the same list around), you need to do so explicitly:
However,
listis already the name of a Python built-in – it’d be better not to use that name for your variable. Here’s a version that doesn’t uselistas a variable name, and makes a copy:Note that I demonstrated two different ways to make a copy of a list above:
[:]andlist().The first,
[:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.The second,
list(), is using the actuallisttype constructor to create a new list which has contents equal to the first list. (I didn’t use it in the first example because you were overwriting that name in your code – which is a good example of why you don’t want to do that!)