Lists are one of the six fundamental data types in the Python programming language. To work effectively with Python, you need to know the functions and methods that work with lists. And that’s what we’ll explain in this article. Show
In Python, lists can be used to store multiple elements in a single variable. Moreover, a single Python iterate list can harbor elements of multiple data types. Lists (like arrays in other programming languages) can also be nested – i.e. lists can contain other lists. Python provides multiple ways to over lists; each one has its benefits and drawbacks. In this article, we shall look at how Python lists are iterated and present an example for each method. If this all seems new, we recommend trying our Learn Programming with Python track to get a head start in Python programming. This track will help you understand the fundamentals of programming, including lists and iteration. Without further delay, let's dive right in! 7 Ways You Can Iterate Through a List in Python1. A Simple for LoopUsing a Python Apple Mango Banana Peach8 loop is one of the simplest methods for iterating over a list or any other sequence (e.g. tuples, sets, or dictionaries). Python for loops are a powerful tool, so it is important for programmers to understand their versatility. We can use them to run the statements contained within the loop once for each item in a list. For example: fruits = ["Apple", "Mango", "Banana", "Peach"] for fruit in fruits: print(fruit) Running the function results in the following output: Apple Mango Banana Peach Here, the Apple Mango Banana Peach8 loop has printed each of the list items. In other words, the loop has called the fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]0 function four times, each time printing the current item in the list – i.e. the name of a fruit. 2. List ComprehensionList comprehension is similar to the for loop; however, it allows us to create a list and iterate through it in a single line. Due to its utter simplicity, this method is considered one of the most robust ways of iterating over Python lists. Check out this article on lists and list comprehension in Python for more details. For now, let’s look at an example: fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits] You’ll notice that we’re using what looks like another for loop: fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]1. The key here is that the command and the fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]2 structure are enclosed with the fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]0 command in square brackets; that’s what makes it a list comprehension. Here’s the output: Apple juice Mango juice Banana juice Peach juice As you can see, we created the fruits list just as we did in the previous example. However, this time we used list comprehension to do two things: add the word ‘juice’ to the end of the list item and print it. 3. A for Loop with range()Another method for looping through a Python list is the fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]4 function along with a Apple Mango Banana Peach8 loop. fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]4 generates a sequence of integers from the provided starting and stopping indexes. (An index refers to the position of elements in a list. The first item has an index of 0, the second list item is 1, and so on.) The syntax of the range function is as follows: range(start, stop, step) The start and step arguments are optional; only the stop argument is required. The step determines if you skip list items; this is set as 1 by default, meaning no items are skipped. If you only specify one parameter (i.e. the stop index), the function constructs a range object containing all elements from 0 to stop-1. Here’s an example that will print the fruit name and its index in the list: fruits = ["Apple", "Mango", "Banana", "Peach"] # Constructs range object containing elements from 0 to 3 for i in range(len(fruits)): print("The list at index", i, "contains a", fruits[i]) This results in the following output: The list at index 0 contains a Apple The list at index 1 contains a Mango The list at index 2 contains a Banana The list at index 3 contains a Peach A slightly different approach would be to print only some of the fruits based on their index. We’d do this by specifying the starting and ending index for the for loop using the fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]4 function: fruits = ["Apple", "Mango", "Banana", "Peach"] # Constructs range object containing only 1 and 2 for i in range(1, 3): print(fruits[i]) Here’s the output: Mango Banana As we asked, it’s returned only those fruits at index 1 and 2; remember, 3 is the stopping point, and 0 is the first index in Python. 4. A for Loop with enumerate()Sometimes you want to know the index of the element you are accessing in the list. The fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]8 function will help you here; it adds a counter and returns it as something called an ‘enumerate object’. This object contains elements that can be unpacked using a simple Python for loop. Thus, an enumerate object reduces the overhead of keeping a count of the number of elements in a simple iteration. Here’s an example: fruits = ["Apple", "Mango", "Banana", "Peach"] for index, element in enumerate(fruits): print(index, ":", element) Running the above code returns this list of the elements and their indexes: Apple Mango Banana Peach0 5. A for Loop with lambdaPython’s fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]9 function is an anonymous function in which a mathematical expression is evaluated and then returned. As a result, fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]9 can be used as a function object. Let’s see how to use fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]9 as we loop through a list. We’ll make a Apple Mango Banana Peach8 loop to iterate over a list of numbers, find each number's square, and save or append it to the list. Finally, we’ll print a list of squares. Here’s the code: Apple Mango Banana Peach1 We use fruits = ["Apple", "Mango", "Banana", "Peach"] [print(fruit + " juice") for fruit in fruits]9 to iterate through the list and find the square of each value. To iterate through Apple juice Mango juice Banana juice Peach juice4, a Apple Mango Banana Peach8 loop is used. Each integer is passed in a single iteration; the Apple juice Mango juice Banana juice Peach juice6 function saves it to Apple juice Mango juice Banana juice Peach juice7. We can make this code even more efficient using the Apple juice Mango juice Banana juice Peach juice8 function: Apple Mango Banana Peach2 After applying the provided function to each item in a specified iterable, Apple juice Mango juice Banana juice Peach juice8 produces a map object (which is an iterator) of the results. Both these codes give the exact same output: Apple Mango Banana Peach3 6. A while LoopWe can also iterate over a Python list using a range(start, stop, step)0 loop. This is one of the first loops beginning programmers meet. It's also one of the easiest to grasp. If you consider the name of the loop, you'll soon see that the term "while" has to do with an interval or time period. The term "loop" refers to a piece of code that is executed repeatedly. So, a range(start, stop, step)0 loop executes until a certain condition is met. In the code below, that condition is the length of the list; the range(start, stop, step)2 counter is set to zero, then it adds 1 every time the loop prints one item in the list. When range(start, stop, step)2 becomes greater than the number of items in the list, the range(start, stop, step)0 loop terminates. Check out the code: Apple Mango Banana Peach4 Can you guess what the output will be? Apple Mango Banana Peach It is important to note the range(start, stop, step)5 in the code above can also be shortened as range(start, stop, step)6. Our code ensures that the condition range(start, stop, step)7 will be satisfied after a certain number of iterations. Ending range(start, stop, step)0 loops properly is critical; you can learn more about how to end loops in Python here. 7. The NumPy LibraryThe methods we’ve discussed so far used a small lists. However, efficiency is essential when you’re working with larger amounts of data. Suppose you have large single-dimensional lists with a single data type. In this case, an external library like NumPy is the best way to loop through big lists. NumPy reduces the overhead by making iteration more efficient. This is done by converting the lists into NumPy arrays. As with lists, the for loop can also be used to iterate over these arrays. It is important to note that the method we present here can only be used for arrays of single data types. Apple Mango Banana Peach6 Running the code above gives the following output: Apple Mango Banana Peach7 Although we’ve used range(start, stop, step)9: for its simplicity in this example, it’s usually better to use fruits = ["Apple", "Mango", "Banana", "Peach"] # Constructs range object containing elements from 0 to 3 for i in range(len(fruits)): print("The list at index", i, "contains a", fruits[i])0 when you’re working with large lists. The fruits = ["Apple", "Mango", "Banana", "Peach"] # Constructs range object containing elements from 0 to 3 for i in range(len(fruits)): print("The list at index", i, "contains a", fruits[i])1 function returns an iterator that can traverse the NumPy array, which is computationally more efficient than using a simple for loop. Time To Practice Lists and Loops in Python!Python loops are useful because they allow you to repeat a piece of code. You'll frequently find yourself in circumstances where you'll need to perform the same operations over and over again; loops help you do so efficiently. You now know many ways to use Python to loop through a list. If you want to practice what you’ve learned (and solidify your understanding of Python) check out our Python Practice Set. The exercises are straightforward and intuitive. Plus, there aren’t many tricky questions, and you will always be able to count on help and hints. So visit this course now and embark on your journey to become a Pythonista. What is the use of for loop in array?A for loop examines and iterates over every element the array contains in a fast, effective, and more controllable way. This is much more effective than printing each value individually: console. log(myNumbersArray[0]); console.
What is a for loop in Python?A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
CAN YOU for loop an array?You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
How do you print an array in Python for loop?This is a simple program to create an array and then to print it's all elements.. #Initialize array.. arr = [1, 2, 3, 4, 5];. print("Elements of given array: ");. #Loop through the array by incrementing the value of i.. for i in range(0, len(arr)):. print(arr[i]),. |