Create a Python Flat Nested List

Home /

Table of Contents

List in Python

A list is a collection of items that are ordered and changeable in python. Lists are written with square brackets and the items inside the list are separated by commas. Each item in a list has an index, which is a numerical value that represents its position in the list. Here is an example of a list:

fruits = ['apple', 'banana', 'mango']

The above list contains three items: ‘apple’, ‘banana’, and ‘mango’. The first item is at index 0, the second item is at index 1, and so on.

You can access the items in a list by referring to their index. For example, to access the first item in the above list:

print(fruits[0])  # Output: 'apple'

You can also use negative indexing to access the items from the end of the list. The last item in a list has an index of -1, the second-to-last item has an index of -2, and so on.

print(fruits[-1]) # Output: 'mango'

Lists are mutable, which means you can change the items in a list. You can add new items to the list, remove items from the list, and change the value of existing items.

fruits.append('orange')  # add 'orange' to the end of the list
fruits.remove('banana')  # remove 'banana' from the list
fruits[0] = 'strawberry' # change the value of the first item

There are many built-in functions and methods that you can use to work with lists, such as ‘len()‘, ‘sort()‘, ‘append()‘, ‘remove()‘, ‘pop()‘, ‘extend()‘, etc. You can also use list comprehension and other techniques to manipulate and transform lists.

Flatten list

A flat list, also known as a flatten list, is a one-dimensional list that contains all the elements of a nested list (a list of lists) without any additional nested lists. In other words, it’s a list that doesn’t contain any sublists.

For example, consider the following nested list:

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

A flat version of the above nested list would be:

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

Flattening a list of lists is a common task in programming and there are several ways to do it in Python, such as using the ‘itertools.chain()‘ method, using list comprehension or using the ‘sum()‘ function with a list comprehension.

Once you have a flat list, it’s easier to perform certain operations on it, such as searching, sorting, and iterating over the elements.

Make a flat list of a list of lists

To make a flat list (also known as flattening a list of lists) in Python, you can use the ‘itertools.chain()‘ method from the ‘itertools‘ module or use list comprehension.

Using ‘itertools.chain()‘:

import itertools

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = list(itertools.chain(*list_of_lists))
print(flat_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

The ‘*‘ operator is used to unpack the list of lists, and ‘itertools.chain()‘ takes each element of the unpacked list and chains them together into one iterable.

Using list comprehension:

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for sublist in list_of_lists for item in sublist]
print(flat_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Both the above methods will give you the same output, a flat list which contains all elements from the original list of lists.

It’s also possible to use the ‘sum()‘ function with a list comprehension, but that only works when the list of lists is not empty, otherwise it will raise a TypeError.

list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = sum(list_of_lists, [])
print(flat_list)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

It’s up to you which one you choose to use, depending on your use case and coding style.

Create Flat Nested List

In Python, you can create a flat nested list by using list comprehension. A flat nested list is a list that contains multiple sub-lists within it, but all the elements are in a single level. Here is an example of how you can create a flat nested list using list comprehension:

# Example 1: Using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]

In this example, ‘nested_list‘ is the list containing sub-lists. The ‘for sublist in nested_list‘ iterates through each sub-list in ‘nested_list‘, and ‘for item in sublist‘ iterates through each item in the current sub-list. Finally, the ‘item‘ is appended to the ‘flat_list‘.

Here is another example where we have a nested list with more than one level of nesting:

# Example 2: Using nested list comprehension
nested_list = [[1, 2, 3], [4, 5, [6, 7]], [8, 9]]

flat_list = [item for sublist1 in nested_list for sublist2 in sublist1 for item in (sublist2 if isinstance(sublist2, list) else [sublist2])]

In this example, we have a nested list that contains sub-lists with multiple levels of nesting. The ‘isinstance(sublist2, list)‘ checks whether the current item is a list or not. If it is a list, then ‘for item in sublist2‘ iterates through each item in the nested list. Otherwise, it appends the item as it is.

Note that, in the above example, we have used nested list comprehension to iterate through multiple levels of nesting.

Share The Tutorial With Your Friends

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article