Python syntax for arrays

7 Ways to Loop Through a List in Python

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.

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 Python

1. A Simple for Loop

Using a Python for 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:

Here, the for loop has printed each of the list items. In other words, the loop has called the print() function four times, each time printing the current item in the list – i.e. the name of a fruit.

2. List Comprehension

List 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: for fruit in fruits . The key here is that the command and the for..in structure are enclosed with the print() command in square brackets; that’s what makes it a list comprehension.

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() function along with a for loop. range() 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:

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 range() function:

fruits = ["Apple", "Mango", "Banana", "Peach"] # Constructs range object containing only 1 and 2 for i in range(1, 3): print(fruits[i])

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 enumerate() 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.

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 lambda

Python’s lambda function is an anonymous function in which a mathematical expression is evaluated and then returned. As a result, lambda can be used as a function object. Let’s see how to use lambda as we loop through a list.

We’ll make a for 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:

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 lambda to iterate through the list and find the square of each value. To iterate through lst1 , a for loop is used. Each integer is passed in a single iteration; the append() function saves it to lst2 .

We can make this code even more efficient using the map() function:

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, map() produces a map object (which is an iterator) of the results.

Both these codes give the exact same output:

6. A while Loop

We can also iterate over a Python list using a while 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 while loop executes until a certain condition is met.

In the code below, that condition is the length of the list; the i counter is set to zero, then it adds 1 every time the loop prints one item in the list. When i becomes greater than the number of items in the list, the while loop terminates. Check out the code:

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?

It is important to note the i = i + 1 in the code above can also be shortened as i += 1 .

7. The NumPy Library

The 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:

Although we’ve used for num in nums : for its simplicity in this example, it’s usually better to use for num in np.nditer(nums): when you’re working with large lists. The np.nditer 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.

Источник

Синтаксис и возможности цикла for Python

Циклы python — for и while представляют собой операторы языка программирования, то есть операторы итерации, которые позволяют повторять код определенное количество раз.

Синтаксис цикла For

Как уже упоминалось ранее, цикл for в Python является итератором, основанным на цикле. Он проходит по элементам list и tuple, строкам, ключам словаря и другим итерируемым объектам.

В Python цикл начинается с ключевого слова for , за которым следует произвольное имя переменной, которое будет хранить значения следующего объекта последовательности. Общий синтаксис for. in в python выглядит следующим образом:

Элементы «последовательности» перебираются один за другим «переменной» цикла; если быть точным, переменная указывает на элементы. Для каждого элемента выполняется «действие».

Пример простого цикла for в Python:

 
 
>>> languages = ["C", "C++", "Perl", "Python"] >>> for x in languages: . print(x) . C C++ Perl Python >>>

Блок else является особенным; в то время как программист, работающий на Perl знаком с ним, это неизвестная конструкция для программистов, которые работают на C и C++. Семантически он работает точно так же, как и в цикле while .

Он будет выполнен только в том случае, если цикл не был «остановлен» оператором break . Таким образом, он будет выполнен только после того, как все элементы последовательности будут пройдены.

Оператор прерывания в python — break

Если в программе цикл for должен быть прерван оператором break , цикл будет завершен, и поток программы будет продолжен без выполнения действий из else .

Обычно фразы break в pyton связаны с условными операторами.

 
 
edibles = ["отбивные", "пельмени", "яйца", "орехи"] for food in edibles: if food == "пельмени": print("Я не ем пельмени!") break print("Отлично, вкусные " + food) else: print("Хорошо, что не было пельменей!") print("Ужин окончен.")

Если мы запустим этот код, получим следующий результат:

Отлично, вкусные отбивные Я не ем пельмени! Ужин окончен.

Удалим «пельмени» из нашего списка еды и получим следующее:

Отлично, вкусные отбивные Отлично, вкусные яйца Отлично, вкусные орехи Хорошо, что не было пельменей! Ужин окончен. 

Оператор пропуска python — continue

Предположим, нам «пельмени» нам нужно просто пропустить и продолжить прием пищи. Тогда нужно использовать оператор continue , для перехода к следующему элементу.

В следующем маленьком скрипте python мы используем continue , чтобы продолжить, итерацию по списку, когда мы сталкиваемся с пельменями.

 
edibles = ["отбивные", "пельмени", "яйца", "орехи"] for food in edibles: if food == "пельмени": print("Я не ем пельмени!") continue print("Отлично, вкусные " + food) else: print("Ненавижу пельмени!") print("Ужин окончен.")

Результат будет следующим:

Отлично, вкусные отбивные Я не ем пельмени! Отлично, вкусные яйца Отлично, вкусные орехи Ненавижу пельмени! Ужин окончен.

Итерация по спискам с функцией range()

Если вам нужно получить доступ к индексам списка, не очевидно как использовать цикл for для этой задачи. Мы можем получить доступ ко всем элементам, но индекс элемента остается недоступным. Есть способ получить доступ как к индексу элемента, так и к самому элементу. Для этого используйте функцию range() в сочетании с функцией длины len() :

Источник

Оцените статью