In Python, you can create a nested list by placing one or more lists inside another list. This allows you to represent a hierarchical structure or store multiple levels of data.
To create a nested list in Python, you can use the following syntax:
nested_list = [ [element1, element2, ...], [element3, element4, ...], ... ]
Here’s an example of creating a nested list with three inner lists:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
You can also create an empty nested list and then append inner lists to it. Here’s an example:
nested_list = []
nested_list.append([1, 2, 3])
nested_list.append([4, 5, 6])
nested_list.append([7, 8, 9])
Create a nested list in Python example
Here are a few examples of creating nested lists in Python:
Example 1: A nested list of strings
nested_list = [['apple', 'banana', 'cherry'],
['orange', 'grapefruit'],
['strawberry']]
print(nested_list)
Output:
Example 2: A nested list of mixed data types
nested_list = [[1, 'apple', True],
['banana', 2.5, False],
[3, 'cherry', True]]
Example 3: A nested list of lists
nested_list = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]
Example 4: Creating an empty nested list and appending inner lists
nested_list = []
nested_list.append([1, 2, 3])
nested_list.append(['apple', 'banana', 'cherry'])
nested_list.append([True, False])
Example 5: A nested list with duplicate elements
nested_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
The structure and elements of a nested list can vary based on your specific requirements.
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.