Open In App

Iterate Over a List of Lists in Python

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Iterating over a list of lists is a common task in Python, especially when dealing with datasets or matrices. In this article, we will explore various methods and techniques for efficiently iterating over nested lists, covering both basic and advanced Python concepts. In this article, we will see how we can iterate over a list of lists in Python.

Iterate Over a Nested List in Python

Below are some of the ways by which we can iterate over a list of lists in Python:

Iterating Over a List of Lists

In this example, a list named `list_of_lists` is created, containing nested lists. Using nested for loops, each element in the inner lists is iterated over, and the `print` statement displays the elements horizontally within each sublist, with each sublist on a new line.

Python3




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


Output

1 2 3 
4 5 6 
7 8 9 


Using List Comprehension

In this example, a nested list named `nested_list` is created. List comprehension is used to flatten the nested structure into a single list named `flattened_list`. The resulting flattened list is then printed, showcasing a concise and powerful approach to list manipulation.

Python3




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


Output

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


Enumerating Over a Nested List

In this example, a list named `languages` is created, representing programming languages. The enumerate() function is utilized in a for loop to iterate over the list, providing both the index and the language during each iteration. The `print` statement displays the indexed list of programming languages with enumeration starting from 1.

Python3




nested_list = [[1, 2, 3], [4, 5], [7, 8]]
  
for i, inner_list in enumerate(nested_list):
    for j, element in enumerate(inner_list):
        print(f"Value at index ({i}, {j}): {element}")


Output

Value at index (0, 0): 1
Value at index (0, 1): 2
Value at index (0, 2): 3
Value at index (1, 0): 4
Value at index (1, 1): 5
Value at index (2, 0): 7
Value at index (2, 1): 8


Using itertools.chain() Function

In this example, the itertools.chain() function is employed to flatten a nested list named `nested_list`. The `*nested_list` syntax is used to unpack the inner lists, and the result is a flattened list, which is then printed.

Python3




from itertools import chain
  
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  
flattened_list = list(chain(*nested_list))
print(flattened_list)


Output

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


Conclusion

So, Overall, understanding the syntax and various operations associated with Python lists is essential for efficient data manipulation and iteration. Whether you are working with a simple list or a list of lists, Python’s list capabilities provide a powerful foundation for data handling.



Previous Article
Next Article

Similar Reads

Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over multiple lists at a time For better understanding
4 min read
Iterate over a list in Python
The List is equivalent to arrays in other languages, with the extra benefit of being dynamic in size. In Python, the list is a type of container in Data Structures, which is used to store multiple data at the same time. Unlike Sets, lists in Python are ordered and have a definite count. In this article, we will see how to iterate over a list in Pyt
7 min read
Python | Ways to iterate tuple list of lists
List is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary.Given a tuple list of lists, write a Python program to iterate through it and get all elements. Method #1: Use itertools.ziplongest C
5 min read
Iterate over a set in Python
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements.There are numerous ways that can be used to iterate over a Set. Some of these ways provide faster time execution as compared to others. Some of these ways include, iterating using for/while loops, comprehensions, iterators and their variat
6 min read
Iterate over characters of a string in Python
In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over the characters of a string in Python. Example #1: Using simple iteration and range() C/C++ Code # Python program to iterate over characters of a string # Code #1 string_name = "geeksforgeeks" # Iterate over the string for el
3 min read
Iterate over words of a String in Python
Given a String comprising of many words separated by space, write a Python program to iterate over these words of the string. Examples: Input: str = "GeeksforGeeks is a computer science portal for Geeks" Output: GeeksforGeeks is a computer science portal for Geeks Input: str = "Geeks for Geeks" Output: Geeks for Geeks Method 1: Using split() Using
4 min read
Python - Iterate over Columns in NumPy
Numpy (abbreviation for 'Numerical Python') is a library for performing large-scale mathematical operations in a fast and efficient manner. This article serves to educate you about methods one could use to iterate over columns in an 2D NumPy array. Since a single-dimensional array only consists of linear elements, there doesn't exists a distinguish
3 min read
How to Iterate over Dataframe Groups in Python-Pandas?
In this article, we'll see how we can iterate over the groups in which a data frame is divided. So, let's see different ways to do this task. First, Let's create a data frame: C/C++ Code # import pandas library import pandas as pd # dictionary dict = {'X': ['A', 'B', 'A', 'B'], 'Y': [1, 4, 3, 2]} # create a dataframe df = pd.DataFrame(dict) # show
2 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
How to iterate over files in directory using Python?
Directory also sometimes known as a folder are unit organizational structure in a system’s file system for storing and locating files or more folders. Python as a scripting language provides various methods to iterate over files in a directory. Below are the various approaches by using which one can iterate over files in a directory using python: M
2 min read
Practice Tags :
three90RightbarBannerImg