Lists are the foundation of Python programming!

Lists, often referred to as one-dimensional arrays, have a lot of uses in Python. This includes storing multiple pieces of information under a single variable name. However, you can also have multiple …

Updated November 1, 2023

Lists, often referred to as one-dimensional arrays, have a lot of uses in Python. This includes storing multiple pieces of information under a single variable name. However, you can also have multiple lists inside another list. That’s where ‘Lists of Lists’ come into play. Here’s a basic guide on creating and working with lists of lists in Python using Markdown format for clarity and simplicity.

To create a list of lists in Python, we use the following syntax:

list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]

You can access items in this list using indices. Here’s how to do it:

print(list_of_lists[0])  # prints [1,2,3]
print(list_of_lists[0][1])  # prints 2

To append an item or a list to another list, you can use the append() method:

list_of_lists.append([10,11,12])
print(list_of_lists)  # prints [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]

To remove an item or a list from the list of lists, you can use the remove() method:

list_of_lists.remove([4, 5, 6])
print(list_of_lists)  # prints [[1, 2, 3], [7, 8, 9], [10, 11, 12]]

You can also use list comprehension to create a new list from an existing one:

new_list = [item for sublist in list_of_lists for item in sublist]
print(new_list) # prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp