how to create a list of lists

My Python code generates a list everytime it loops:

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

But I want to save each one - I need a list of lists right?

So I tried:

list[i] = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1) 

But Python now tells me that "list" is not defined. I'm not sure how I go about defining it. Also, is a list of lists the same as an array??

Thank you!

5

5 Answers

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = [] >>> l.append([1,2,3]) >>> l.append([4,5,6]) >>> l [[1, 2, 3], [4, 5, 6]] 
3

Create your list before your loop, else it will be created at each loop.

>>> list1 = [] >>> for i in range(10) : ... list1.append( range(i,10) ) ... >>> list1 [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]] 

Use append method, eg:

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

First of all do not use list as a variable name- that is a builtin function.

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-

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

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.

The first can be referenced with my_list[0] and the second with my_list[1]

Just came across the same issue today...

In order to create a list of lists you will have firstly to store your data, array, or other type of variable into a list. Then, create a new empty list and append to it the lists that you just created. At the end you should end up with a list of lists:

list_1=data_1.tolist() list_2=data_2.tolist() listoflists = [] listoflists.append(list_1) listoflists.append(list_2) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like