how to iterate through a 2d list in python

10 ways to iterate through a list in python

The list is similar to array in other languages except for python, which provides the extra benefit of being dynamic in size nature. In Python, the list is a type of  Data Structures, which is used to store different and multiple kinds of data at the same time.

10 ways to iterate through a list in python
10 ways to iterate through a list in python

There are many ways to iterate over a list in Python language. how to iterate through a 2d list in python

  1.  Using For loop in python
  2.  For loop and range() in python
  3.  Using while loop in python
  4.  Using list comprehension  ways in python
  5.  Using enumerate() in python
  6.  Using Numpy in python
  7. Using iterable without index in python
  8. Using general way via index
  9. Using the enumerate type function
  10. Using negative indexes in python

Method #1: Using For loop in python

# Python3 code to iterate over a list in python
list = [1, 3, 5, 8, 9] 
# Using for loop 
for n in list: 
print(n) 

Output:

1
3
5
8
9

Method #2: For loop and range() in python

In case we want to use the traditional For loop and range() in python which iterates from number x to number y.

# Python3 code to iterate over a list in python
num = [1, 3, 5, 8, 9] 
# getting length of list in python 
length = len(num) 
# How to Iterating the index 
for i in range(length): 
print(list[i]) 

learn pandas in python
Output:

1
3
5
8
9

Method #3: Using while loop in python

# Python3 code to iterate over a list in python
num = [1, 3, 5, 8, 9] 
# Getting length of list in python
length = len(num) 
i = 0
# Iterating using while loop in python
while i < length: 
print(num[i]) 
i += 1

Output:

1
3
5
8
9

Method #4: Using list comprehension  ways in python

# Python3 code to iterate over a list in python
num = [1, 3, 5, 8, 9] 
# Using list comprehension in python
[print(i) for i in num] 

Output:

1
3
5
8
9

Method #5: Using enumerate() in python
suppose if we want to convert the list of set into an iterable list of tuples, then you can use the enumerate() function in python.

# Python3 code to iterate over a list in python
num = [1, 3, 5, 8, 9] 
# Using enumerate() function in python 
for i, val in enumerate(num): 
print (i, “,”,val) 

Output:

0 , 1
1 , 3
2 , 5
3 , 8
4 , 9 

(more…)

Continue Readinghow to iterate through a 2d list in python