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 iterate 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 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 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: 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 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"] # 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 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: 0 : Apple 1 : Mango 2 : Banana 3 : Peach 5. A for Loop with lambdaPython’s We’ll make a lst1 = [1, 2, 3, 4, 5] lst2 = [] # Lambda function to square number temp = lambda i:i**2 for i in lst1: # Add to lst2 lst2.append(temp(i)) print(lst2) We use We can make this code even more efficient using the
lst1 = [1, 2, 3, 4, 5] lst1 = list(map(lambda v: v ** 2, lst1)) print(lst1) After applying the provided function to each item in a specified iterable, Both these codes give the exact same output: [1, 4, 9, 16, 25] 6. A while LoopWe can also iterate over a Python list using a In the code below, that condition is the length of the list; the fruits = ["Apple", "Mango", "Banana", "Peach"] i = 0 while i < len(fruits): print(fruits[i]) i = i + 1 Can you guess what the output will be? Apple Mango Banana Peach It is important to note the Our code ensures that the condition 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. import numpy as np nums = np.array([1, 2, 3, 4, 5]) for num in nums: print(num) Running the code above gives the following output: 1 2 3 4 5 Although we’ve used 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. Can you use a for loop in a list Python?In Python, we can loop over list elements with for and while statements, and list comprehensions.
How can I create a list in Python?In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.).
How do you add a loop to a list in Python?“how to add to a list in python for loop” Code Answer's. for i in range(5):. a. append(i). print(a). # [0, 1, 2, 3, 4]. How do you create a list of tuples in a for loop?Method 2: Using For loop with enumerate() method
Enumerate() method adds a counter to an iterable and returns it in a form of enumerating object. So we can use this function to create the desired list of tuples.
|