How to Create a List of Lists in Python?

How do I create a list of lists in Python?

My Python code generates a list every time it loops:

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

But I want to save each list generated, so I need to create a list of lists in Python, right?

So I tried:

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

But Python gives me an error saying that “list” is not defined. I’m not sure how to define it. Also, is a list of lists in Python the same as an array?

Thank you!

Hey there! I’ve come across this issue before and can definitely help. To properly create a list of lists in Python, you need to initialize an empty list before the loop where you generate your lists. Here’s how you can do it:

list_of_lists = []  # Initialize an empty list to store lists  
for i in range(10):  # Loop through your iterations  
    new_list = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname', 'float')], skip_header=1)  
    list_of_lists.append(new_list)  # Append the new list to list_of_lists  

This approach ensures that list_of_lists will store each list generated in the loop. By the end of the loop, you’ll have your list of lists. Simple, right?

Great point, Shilpa! If you want a more concise way to create a list of lists in Python, you can use list comprehensions. They’re compact and pretty elegant for cases like this:

list_of_lists = [np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname', 'float')], skip_header=1) for i in range(10)]  

This one-liner does the same as the loop Shilpa mentioned—it generates and appends each list to list_of_lists. A little cleaner if you’re comfortable with comprehensions!

Adding to what Vindhya and Shilpa said—both great suggestions—one critical tip: Avoid using list as a variable name. It’s a built-in Python type, and overwriting it can cause issues down the line. Instead, use something like list_of_lists or another descriptive name.

Here’s a solid approach to do it:

list_of_lists = []  # Initialize list_of_lists  
for i in range(10):  # Loop through your iterations  
    new_list = np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname', 'float')], skip_header=1)  
    list_of_lists.append(new_list)  # Append the new list  

This ensures that your variable name is safe and your code is robust. And to answer your last question—no, a list of lists in Python is not the same as an array. Lists are more flexible, but arrays (like those in NumPy) are optimized for numerical operations.