- Python Program to Iterate Over an Array
- Arrays in Python
- Using For Loop
- Example
- Output
- Example
- Output
- Example
- Output
- Using While Loop
- Example
- Output
- Using Enumerate()
- Example
- Output
- 6 Ways to Iterate through a List in Python (with Code)
- What is a List in Python?
- 6 Ways to Iterate through a List in Python
- Using for loop
- Using loop and range() function
- Using While loop
- Using list comprehension
- Using enumerate() function
- Using Numpy function
- Conclusion
- FavTutor - 24x7 Live Coding Help from Expert Tutors!
- Ways to Iterate Through List in Python
- Upskill 2x faster with Educative
- 1. Iterate through list in Python using range() method
- 2. Iterate through list in Python using a for Loop
- 3. List Comprehension to iterate through a list in Python
- 4. Iterate through list in Python with a while loop
- 5. Python NumPy to iterate through List in Python
- 6. Python enumerate() method to iterate a Python list
- 7. Iterating a Python list using lambda function
- Conclusion
- References
Python Program to Iterate Over an Array
An array is a data structure consisting of a set of elements (values) of the same data type, each element is identified by an index value. And the elements can be directly accessed by using their index numbers.
Arrays in Python
Python does not have a native array data structure. Instead, we can use the list data structure, NumPy, or array modules.
Here we will use list an array −
The above array has 5 elements and each element is identified by an index value, starting from 0 to n-1, where n is the total number of elements.
Iterating over an array means accessing the array elements one by one. In the article below, we will see multiple ways to iterate over an array in Python.
Using For Loop
This is the easiest method to iterate an array in python programming. Here the for loop iterates all the array elements.
Example
In this example, The variable ele is the loop variable it stores the element corresponding to the each iteration. Rather than using the index number to accasses one by one element, here we can simply loop through and disply the array elements in the output.
lst = [1, 2, 3, 4, 5, 6] print ("The original array is: ",lst) # iterate over an array using the for loop print("Iterate Over an Array: ") for ele in lst: print(ele)
Output
The original array is: [1, 2, 3, 4, 5, 6] Iterate Over an Array: 1 2 3 4 5 6
In the above example the array elements are iterated one by one using the for loop.
Example
In this example, we will iterate the array elements using the for loop and range() function together.
lst = [1, 2, 3, 4, 5, 6] print ("The original array is: ",lst) # iterate over an array using the for loop print("Iterate Over an Array: ") for i in range(len(lst)): print(lst[i])
Output
The original array is: [1, 2, 3, 4, 5, 6] Iterate Over an Array: 1 2 3 4 5 6
Here, the variable “i” varies from 0 to length(array)-1, and it represents the index of the array elements.
Example
In this example, we will take an array of strings and we will iterate all string elements using the for loop.
lst = ['P', 'y', 't', 'h', 'o', 'n'] print ("The original array is: ",lst) # iterate over an array using the for loop print("Iterate Over an Array: ") for i in range(len(lst)): print(lst[i])
Output
The original array is: ['P', 'y', 't', 'h', 'o', 'n'] Iterate Over an Array: P y t h o n
Using While Loop
By using a while loop we can iterate the array elements. In python, while Loop generates the iterations repeatedly until a given condition is satisfied.
Example
lst = [1, 2, 3, 4, 5, 6] print ("The original array is: ",lst) # iterate over an array using the While loop print("Iterate Over an Array: ") i = 0 while i< len(lst): print(lst[i]) i += 1
Output
The original array is: [1, 2, 3, 4, 5, 6] Iterate Over an Array: 1 2 3 4 5 6
Note: The while loop will become an infinite loop if we forgot to increase the index value (i += 1).
Using Enumerate()
Enumerate() is a python built-in function, it takes an iterable-like array and returns a tuple containing a count and the values obtained from iterating over an iterable. Following is the syntax of this method –
- Iterable – An iterable object (list, string, etc.,).
- Start – A Number, default value is 0.
Example
In this example we will display the element along with the corresponding index value using the enumerate() function.
lst = [1, 2, 3, 4, 5, 6] print ("The original array is: ",lst) # iterate over an array using the for loop and enumerate() function print("Iterate Over an Array: ") for i, ele in enumerate(lst): print(i, ':', ele)
Output
The original array is: [1, 2, 3, 4, 5, 6] Iterate Over an Array: 0 : 1 1 : 2 2 : 3 3 : 4 4 : 5 5 : 6
These are a few of the ways to iterate over an array in Python.
6 Ways to Iterate through a List in Python (with Code)
In this article, we will study what is a list in python language and different ways to iterate through a list in python programming along with the python code for the same. So, let’s start!
What is a List in Python?
List in python language is used to store multiple elements in a single variable. Lists are one of the 4 data types in python language along with tuple, set, and dictionary. List in Python is created by putting elements inside the square brackets, separated by commas. A list can have any number of elements and it can be of multiple data types. Also, all the operation of the string is similarly applied on list data type such as slicing, concatenation, etc. Also, we can create the nested list i.e list containing another list.
6 Ways to Iterate through a List in Python
There are multiple ways through which we can iterate the list in python programming. Let us study them one by one below:
Using for loop
The easiest method to iterate the list in python programming is by using them for a loop. The method of the iterating list using for loop is as given below
list = [1, 2, 3, 4, 5] # Iterating list using for loop for i in list: print(i)
The output of the above code is as given below:
Using loop and range() function
Another method to iterate the list while programming in python is by using the loop and range() function together. Iterating the list using this method is not recommended if iteration using for loop(method 1) is possible. The method to do so is as given below:
list = [1, 2, 3, 4, 5] # getting length of list using len() function length = len(list) # using for loop along with range() function for i in range(length): print(list[i])
The output of the above code is as given below:
Using While loop
We can also iterate the list in python language using a while loop. The method to use while loop for the iterating list is as given below:
list = [1, 2, 3, 4, 5] # Getting length of list using len() function length = len(list) i = 0 while i length: print(list[i]) i += 1
The output of the above code is as given below:
Using list comprehension
This is the most concrete way to iterate the list while programming in the python language. The method to iterate list using list comprehension is as given below:
list = [1, 2, 3, 4, 5] # Iterating list using list comprehension [print(i) for i in list]
The output of the above code is as given below:
Using enumerate() function
There are few times when you may need the display the index of the element along with the element in the list itself. In such cases, we use the enumerate() function for the iteration of the list. The method to use the enumerate() function to iterate the list is as given below:
list = [1, 3, 5, 7, 9] # Using enumerate() function to iterate the list for i, val in enumerate(list): print (i, ",",val)
The output of the above code is as given below:
Using Numpy function
All the methods that we discussed till now are generally preferable for small or say single-dimensional lists. But when it comes to large n-dimensional lists it is advisable to use an external library such as NumPy for iterating lists. The method to use the Numpy function for iterating lists is as given below:
# Importing external library import numpy as np a = np.arange(5) for x in np.nditer(a): print(x)
The output of the above code is as given below:
Conclusion
Therefore, in this article, we studied what is the list in python programming and different methods to iterate the list while programming in python. Also, we learned the code to use that method by an example and its respective output.
FavTutor - 24x7 Live Coding Help from Expert Tutors!
About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.
Ways to Iterate Through List in Python
In this tutorial, we’ll go over how to iterate through list in Python. Python List is basically an ordered data structure which enables us to store and manipulate the data in it.
Either of the following ways can be referred to iterate over a list in Python:
Upskill 2x faster with Educative
Supercharge your skillset with Educative Python courses → use code: ASK15 to save 15%
1. Iterate through list in Python using range() method
Python’s range() method can be used in combination with a for loop to traverse and iterate over a list in Python.
The range() method basically returns a sequence of integers i.e. it builds/generates a sequence of integers from the provided start index up to the end index as specified in the argument list.
- start (upper limit): This parameter is used to provide the starting value/index for the sequence of integers to be generated.
- stop (lower limit): This parameter is used to provide the end value/index for the sequence of integers to be generated.
- step (optional): It provides the difference between each integer from the sequence to be generated.
The range() function generates the sequence of integers from the start value till the end/stop value, but it doesn’t include the end value in the sequence i.e. it doesn’t include the stop number/value in the resultant sequence.
lst = [10, 50, 75, 83, 98, 84, 32] for x in range(len(lst)): print(lst[x])
In the above snippet of code, the list is iterated using range() function which traverses through 0(zero) to the length of the list defined.
2. Iterate through list in Python using a for Loop
Python for loop can be used to iterate through the list directly.
for var_name in input_list_name:
lst = [10, 50, 75, 83, 98, 84, 32] for x in lst: print(x)
3. List Comprehension to iterate through a list in Python
Python List Comprehension is an indifferent way of generating a list of elements that possess a specific property or specification i.e. it can identify whether the input is a list, string, tuple, etc.
[expression/statement for item in input_list]
lst = [10, 50, 75, 83, 98, 84, 32] [print(x) for x in lst]
4. Iterate through list in Python with a while loop
Python while loop can also be used to iterate the list in a similar fashion as that of for loops.
while(condition) : Statement update_expression
lst = [10, 50, 75, 83, 98, 84, 32] x = 0 # Iterating using while loop while x < len(lst): print(lst[x]) x = x+1
5. Python NumPy to iterate through List in Python
Python NumPy Arrays can also be used to iterate a list efficiently.
Python numpy.arange() function creates a uniform sequence of integers.
Syntax for numpy.arange() function:
numpy.arange(start, stop, step)
- start : This parameter is used to provide the starting value/index for the sequence of integers to be generated.
- stop : This parameter is used to provide the end value/index for the sequence of integers to be generated.
- step : It provides the difference between each integer from the sequence to be generated.
The numpy.nditer(numpy_array) is a function that provides us with an iterator to traverse through the NumPy array.
import numpy as np n = np.arange(16) for x in np.nditer(n): print(x)
In the above snippet of code, np.arange(16) creates a sequence of integers from 0 to 15.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
6. Python enumerate() method to iterate a Python list
Python enumerate() function can be used to iterate the list in an optimized manner.
The enumerate() function adds a counter to the list or any other iterable and returns it as an enumerate object by the function.
Thus, it reduces the overhead of keeping a count of the elements while the iteration operation.
enumerate(iterable, start_index)
- start_index : It is the index of the element from which the counter has to be recorded for the iterating iterable.
lst = [10, 50, 75, 83, 98, 84, 32] for x, res in enumerate(lst): print (x,":",res)
0 : 10 1 : 50 2 : 75 3 : 83 4 : 98 5 : 84 6 : 32
7. Iterating a Python list using lambda function
Python’s lambda functions are basically anonymous functions.
lambda parameters: expression
The lambda function along with a Python map() function can be used to iterate a list 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, respectively.
lst = [10, 50, 75, 83, 98, 84, 32] res = list(map(lambda x:x, lst)) print(res)
In the above snippet of code, lambda x:x function is provided as input to the map() function. The lambda x:x will accept every element of the iterable and return it.
The input_list (lst) is provided as the second argument to the map() function. So, the map() function will pass every element of lst to the lambda x:x function and return the elements.
Conclusion
In this article. we have unveiled the various techniques to iterate a Python List.