Python: list of lists

Python: list of lists

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 – itd be better not to use that name for your variable. Heres a version that doesnt use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    if len(a_list)>3:
        listoflists.append((list(a_list), a_list[0]))
print listoflists

Note that I demonstrated two different ways to make a copy of a list above: [:] and list().

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 actual list type constructor to create a new list which has contents equal to the first list. (I didnt use it in the first example because you were overwriting that name in your code – which is a good example of why you dont want to do that!)

I came here because Im new with python and lazy so I was searching an example to create a list of 2 lists, after a while a realized the topic here could be wrong…
this is a code to create a list of lists:

listoflists = []
for i in range(0,2):
    sublist = []
    for j in range(0,10)
print listoflists

this the output
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)],
[(1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9)]

The problem with your code seems to be you are creating a tuple with your list and you get the reference to the list instead of a copy. That I guess should fall under a tuple topic…

Python: list of lists

First, I strongly recommend that you rename your variable list to something else. list is the name of the built-in list constructor, and youre hiding its normal function. I will rename list to a in the following.

Python names are references that are bound to objects. That means that unless you create more than one list, whenever you use a its referring to the same actual list object as last time. So when you call

listoflists.append((a, a[0]))

you can later change a and it changes what the first element of that tuple points to. This does not happen with a[0] because the object (which is an integer) pointed to by a[0] doesnt change (although a[0] points to different objects over the run of your code).

You can create a copy of the whole list a using the list constructor:

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

Or, you can use the slice notation to make a copy:

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

Leave a Reply

Your email address will not be published. Required fields are marked *