Posted By: Anonymous
Running the code
listoflists =  list =  for i in range(0,10): list.append(i) if len(list)>3: list.remove(list) listoflists.append((list, list)) print listoflists
[([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 is not. Can someone explain what’s going on here and suggest a way to fix this? I’d like to output
[(,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:
list is 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 use
list as a variable name, and makes a copy:
listoflists =  a_list =  for i in range(0,10): a_list.append(i) if len(a_list)>3: a_list.remove(a_list) listoflists.append((list(a_list), a_list)) print listoflists
Note that I demonstrated two different ways to make a copy of a list above:
[:], 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.
list(), is using the actual
list type 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!)