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 - 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

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 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!)

join list of lists in python

import itertools
a = [['a','b'], ['c']]
print(list(itertools.chain.from_iterable(a)))

This gives

['a', 'b', 'c']

how to create a list of lists

Use append method, eg:

lst = []
line = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1)
lst.append(line)

Slicing list of lists in Python

With numpy it is very simple - you could just perform the slice:

In [1]: import numpy as np

In [2]: A = np.array([[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]])

In [3]: A[:,:3]
Out[3]:
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])

You could, of course, transform numpy.array back to the list:

In [4]: A[:,:3].tolist()
Out[4]: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Assign values to a list of lists

The correct way to pre-dimension the list of lists is as follows:

a, b = 2, 3

matrix = [[[None for _ in range(2)]
for _ in range(a)]
for _ in range(b)]

for i in range(b):
for j in range(a):
print(i, j)
matrix[i][j] = [i, j]
print(matrix)

So the output is as expected:

0 0
0 1
1 0
1 1
2 0
2 1
[[[0, 0], [0, 1]], [[1, 0], [1, 1]], [[2, 0], [2, 1]]]

Adding a list to a list of lists

You can use append to add an element to the end of the list, but if you want to add it to the front (as per your question), then you'll want to use fooList.insert( INSERT_INDEX, ELEMENT_TO_INSERT )

Explicitly

>>> list_of_lists=[[1,2,3],[4,5,6]]
>>> list_to_add=["A","B","C"]
>>> list_of_lists.insert(0,list_to_add) # index 0 to add to front
>>> print list_of_lists
[['A', 'B', 'C'], [1, 2, 3], [4, 5, 6]]

There is more information regarding List API here.



Related Topics



Leave a reply



Submit