Lists

Traversing Lists

Lists are basically equal to arrays in other languages. However, they do have the extra benefit of being dynamic in size. In Python, the list is a kind of container in Data structures. It comes in use for storing numerous data at the same time. Contrasting to sets, in Python, lists are ordered and have a definite count. Moreover, there are various ways for traversing lists in Python. Through this article, we will take a look at the various ways of traversing lists in Python.

traversing

Methods of Traversing Lists

Here are the methods which one can refer to for traversing lists in Python:

  • Python range () method
  • List Comprehension
  • Python enumerate () method
  • Lambda function
  • Python NumPy module
  • By using a for Loop
  • By using a while Loop

Using For Loop

                    

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Using for loop

for i in list:

print(i)

 

Output:

 

Browse more Topics under Lists

Using For Loop and Range ()

If you wish to use the traditional for loop which iterates from number x to number y.

                    

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# getting length of list

length = len(list)

# Iterating the index

# same as 'for i in range(len(list))'

for i in range(length):

print(list[i])

 

Output:

 

It is essential to remember that it is not recommended to iterate by making use of the index if one can iterate over the elements (like how it is done in the first method).

Using While Loop 

                    

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Getting length of list

length = len(list)

i = 0

# Iterating using while loop

while i < length:

print(list[i])

i += 1

 

Output:

 

Using List Comprehension

This one is possibly the most concrete way.

                    

# Python3 code to iterate over a list

list = [2, 4, 6, 8, 10]

# Using list comprehension

[print(i) for i in list]

 

Output:

 

Using Enumerate()

If you wish to convert the list into an iterable list of tuples (or get the index on the basis of a condition check, for instance, in linear search, one might want to save the index of minimum element), one can use the enumerate () function.

                    

# Python3 code to iterate over a list

list = [1, 3, 5, 7, 9]

# Using enumerate()

for i, val in enumerate(list):

print (i, ",",val)

 

Output:

                    

0 , 1

1 , 3

2 , 5

3 , 7

4 , 9

 

You can also use the second method for finding the index. However, the first method cannot be used unless an extra variable is incremented every iteration. Moreover, the fifth method gives a concise representation of this indexing.

Using Numpy

For every large n-dimensional list (for instance an image array), sometimes, it is better to make use of an external library like numpy.

                    

# Python program for

# iterating over array

import numpy as toppr

# creating an array using

# arrange method

a = toppr.arange(9)

# shape array with 3 rows

# and 4 columns

a = a.reshape(3, 3)

# iterating an array

for x in toppr.nditer(a):

print(x)

 

Output:

 

One can make use of np.ndenumerate() for mimicking the behaviour of enumerating. Further, the extra power of numpy comes from the fact that one can even control the way for visiting the elements (Fortran order rather than C order, say :)) however the one caveat is that the np.nditer treats the array as read-only by default. Thus, one must pass extra flags like op_flags=[‘readwrite’] for it to be able to modify elements.

Using Lambda Function

Lambda functions in Python are essentially anonymous functions.

Syntax:

Lambda parameters: expression

  • expression: The iterable which is to be evaluated.

The lambda function along with a Python map() function can come in use for traversing lists easily.

Python map () method accepts a function as a parameter and returns a list.

The input function to the map () method gets called with every element of the iterable and it returns a new list with all the elements returned from the function, individually.

Example:

lst = [20, 40, 85, 93, 99, 85, 31]

res = list(map(lambda x:x, lst))

print(res)

In the snippet of code mentioned above, you see how the lambda x:x function is given as input to the map() function. Thus, the lambda x:x accepts every element of the iterable and returns it.

The input_list (lst) is given as the second argument to the map() function. Thus, the map() function will pass every element of lst to the lambda x:x function and return the elements.

Output:

[20, 40, 85, 93, 99, 85, 31]

 FAQ on Traversing Lists

Question 1: What is traversing a list in Python?

Answer 1: The range () method of Python can come in use in combination with a for loop for traversing and iterating over a list in Python. Further, the range () method basically returns a sequence of integers. In other words, it builds/produces a sequence of integers from the provided start index up to the end index as stated in the argument list.

Question 2: How do I iterate over a list in Python?

Answer 1: In order to iterate over a list in Python, begin by using a nested for-loop iterated through a nested list. After that, make use of a for-loop for iterating through every element of a list. Moreover, if this list comprises other lists, use another for-loop for iterating through the elements in these sublists.

Question 3: What are lists in Python?

Answer 3: A list refers to a data structure in Python that is mutable or changeable, ordered sequence of elements. An item is each element or value that is inside of a list. Similar to how strings define as characters between quotes, lists get defined by having values between square brackets [ ].

Question 4: How do I make a list in Python?

Answer 4: In Python, a list gets created when we place all items (elements) inside the square brackets of [] which is separated by commas. It may have any number of items and they may be of various types such as integer, float, string and more.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.