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), ...

Aug 2, 2018 in Python 609 views

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:

listoflists.append((list[:], list[0]))

However, 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[0])

listoflists.append((list(a_list), a_list[0]))

print listoflists
• 15,520 points

Python: Sort list of lists numerically

You can try and De-dupe it with ...READ MORE

+1 vote

Count the frequency of an item in a python list

To count the number of appearances: from collections ...READ MORE

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

Where can I get the list of Python keywords?

Just import a module “keyword”. Here you ...READ MORE

how can i randomly select items from a list?

You can also use the random library's ...READ MORE

+1 vote

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

Lowercase in Python

You can simply the built-in function in ...READ MORE