Python: list of lists

0 votes

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 by Priyaj
• 56,160 points
29 views

1 answer to this question.

0 votes
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
answered Aug 2, 2018 by bug_seeker
• 15,310 points

Related Questions In Python

0 votes
1 answer

Python: Sort list of lists numerically

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

answered May 20 in Python by SDeb
• 12,200 points
31 views
+1 vote
4 answers

Count the frequency of an item in a python list

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

answered Oct 18, 2018 in Python by tinitales
141 views
0 votes
1 answer

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

answered Apr 17, 2018 in Python by anonymous
525 views
0 votes
1 answer

Where can I get the list of Python keywords?

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

answered Apr 19, 2018 in Python by aayushi
• 750 points
14 views
+1 vote
2 answers

how can i count the items in a list?

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

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 123 views
+4 votes
6 answers
0 votes
1 answer

When to use %r instead of %s in Python? [duplicate]

The %s specifier converts the object using ...READ MORE

answered Aug 2, 2018 in Python by bug_seeker
• 15,310 points
46 views
0 votes
1 answer

Create an empty list in python with certain size

Try this instead: lst = [None] * 10 The ...READ MORE

answered Aug 2, 2018 in Python by bug_seeker
• 15,310 points
101 views