Nested lists in python with code examples.

Omar
2 min readNov 26, 2023

Nesting lists in Python refers to placing one list within another list. This allows you to create hierarchical data structures and represent complex relationships between data elements. Here’s how to nest lists in Python with code examples:

Creating Nested Lists:

To create a nested list, simply include a list as an element within another list. For instance, let’s create a list of fruits, each of which has a sublist of colors associated with it:

Python

fruits = [
['apple', ['red', 'green']],
['banana', ['yellow']],
['orange', ['orange', 'red']]
]

Here, the fruits list contains three elements, each of which is a list itself. The first sublist represents an apple with its associated colors, the second sublist represents a banana with its associated color, and so on.

Accessing Nested List Elements:

To access elements within a nested list, you can use nested indexing. For example, to access the color ‘red’ associated with the apple, you would use the following index:

Python

color = fruits[0][1][0]
print(color) # Output: red

This breaks down as follows:

  • fruits[0] accesses the first element of the fruits list, which is the sublist for apples.
  • fruits[0][1] accesses the second element of the apple sublist, which is the sublist of associated colors.
  • fruits[0][1][0] accesses the first element of the colors sublist, which is the color 'red'.

Nested indexing allows you to navigate through nested lists to reach specific elements deep within the structure.

Common Operations on Nested Lists:

Common operations like appending, removing, and slicing can be performed on nested lists as well. The process is similar to that of regular lists, but with additional nested indexing:

  • Appending: To append an element to a nested sublist, you can use nested indexing to locate the desired sublist and then use the append() method.

Python

fruits[2][1].append('purple')  # Appends 'purple' to the orange's colors
  • Removing: To remove an element from a nested sublist, you can use nested indexing to locate the desired sublist and then use the remove() method.

Python

fruits[1][0] = 'banana peel'  # Replaces 'banana' with 'banana peel'
  • Slicing: To slice a nested sublist, you can use nested indexing to locate the desired sublist and then use slicing syntax.

Python

colors_sublist = fruits[1][1][1:]  # Extracts 'yellow' from the banana's colors

Nested lists provide a powerful way to structure complex data and organize it in a hierarchical manner. By understanding how to create, access, and manipulate nested lists, you can effectively model real-world relationships and perform sophisticated data analysis.

--

--

Omar

Passionate teacher fueling minds through books. Inspiring students to explore, learn, and grow. Dedicated to sharing knowledge and nurturing curiosity.