News
Seven days of Black Friday madness — great deal from Serverspace!

THE NEW YEAR
WHEEL OF FORTUNE

Spin the wheel and win a guaranteed prize right now!

By registering, you are signing up to receiving emails.
DF
February 20 2023
Updated December 11 2024

For loop in Python 3

Linux Ubuntu

Introduction

In programming, a For loop is known as a loop with a known number of repetitions. But in Python, this loop is a more general statement. This means that the For loop is used when the number of iterations is known before entering the loop, as opposed to the While loop, which is based on conditions.

Preparations before we start

Before we can start, we need to do two steps:

  • Install OC running on Ubuntu/Debian/CentOS and make a first configuration of system;
  • Install and configure virtual environment on Python.

Loop "For"

The For loop construction looks like this:

for 'variable' in 'sequence':
'action'

Let's look on an execution a loop inside the Python command interpreter.
We'll write a small programm, the variable n is assigned after it and it is going to print numbers from 6 to 11 and using the print().

for n in range(6,11):
print(n)

For loop Python — Executing code in the shell

In programming, indexing of numbers starts with 0, for this reason, as a result, we see 5 different values that range from six to eleven.

Using range() in a loop "For"

One of the built-in sequences is range() to control how many times our loop will iterate.
range() has three parameters:

  • Start – is the beginning of the sequence (optional parameter and default value 0)
  • Stop – is the sequence stop point (required)
  • Step – is a sequence step (optional parameter and default value 1).

Consider the code with a for loop in which we assign the variable n and the value 15 (the stop parameter) to range() so that the sequence is in this range:

for n in range(15):
print(n)

To stop the loop, parameter 15 was specified, so as a result we got 15 values ​​from 0 to 14, excluding the number 15.

Let's look at the code using the range(start/stop) parameters, define a for loop, assign the variable n, and provide the values ​​as the start and stop parameters.

for n in range(10,15):
print(n)

For loop Python — Executing code using the stop parameter

When we determined the start and stop point, we got a result in the range from 10 to 15, excluding the number 15.

The step parameter is used to specify the step between the start and stop values. Consider the use of steps in the range in the following code, declare the for loop and the variable n in it, assign values ​​to the start/step/stop parameters:

for n in range(25,50,5):
print(n)

For loop Python — Using the step parameter

The result is 5 different values ​​in the range 25-50 using the value 5 as steps.
You can specify a negative number as the step parameter, as shown in the following example. Let's declare a for loop and a variable, assign the values ​​1000,900,-10 to the range parameters. To iterate in reverse order:

for n in range(1000,900,-10):
print(n)

For loop Python — Result of reverse iteration

We looked at a program where the starting point is 1000 and using reverse iteration got values ​​up to 910.

Using a List in a Loop

In loops, you can use a list as iteration parameters. Instead of range(), you can designate a variable before the for loop and use the variable after in.

Consider the code with a list variable that accepts several words, then declare a for loop with a list variable and go through the data from this list:

list = ['one', 'two', 'three', 'four']

for list in list:
print(list)

For loop Python — The result of using lists as data

In this example, we considered calling data from a list designated in advance. Instead of the list variable, we could use another variable, but the result would be the same.
Because lists and other data types are iterable, they can be combined with the range() function.

Let's select a variable from the example above, declare a for loop with the item variable, specify the length of the list list in the range() parameters. In the next line, using append, add the word five to the list of the variable list:

list = ['one', 'two', 'three', 'four', 'five']

for item in range(len(list):
list.append('six')

print(list)

For loop Python — List output with added word six

In this example, we have added 5 words six equal to the number of words from list.

We can also use the for loop to create a list with different values. In the following example, let's denote the numbers variable, in which we will declare a list. Let's add a for loop and parameter 25 to the range() function. In the next line, we write a function to initialize our empty list with the value n, which will complement the list:

numbers = [ ]
for n in range(25):
numbers.append(n)

print(numbers)

For loop Python — Result of the padding list

In the example, we considered a variable without a list, then added a loop in which the range is from 0 to 25 and using append, +1 value is added to 0 and beyond.
In the same way, we can iterate over a string with characters.

Let's declare the word variable and assign the word quickly to it, using the for loop, let's iterate over the word:

word = 'quickly'

for letter in word:
print(letter)

For loop Python — Line iteration

In the example above, the for loop iterated over the word quickly and split it into lines.

You can use a dictionary in a for loop. As you know, the dictionary uses the key, the first word before the colon, followed by the word assigned to the key. To properly call a key value through colons, consider the following example:

list_dict = {'name': 'ServerSpace', 'year': '2022'}

for key in list_dict:
print(key + ':' + list_dict[key])

For loop Python — 5Calling keywords using a colon

In the example above, the variable key was used to represent the key, and list_dict[key] was used to represent the values.

Nested For Loops

A nested loop is a loop inside a for loop and the nested loop construct is as follows:


for 'first variable to iterate' in 'source loop'
'action'
for 'second variable to iterate' in 'nested loop'
'action'

The program first executes the first iteration of the original loop, then goes to the outer loop and executes all iterations, returns to the original loop and executes the next iteration, and so on until the end of the iteration of the original loop. Consider in the following example, we will declare a variable num with integer data types and let with characters.

In the original loop, declare the for loop and the num variable, in the outer let:

num = [10, 15, 25]
let = ['w', 's', 'x']

for number in num:
print(number)
for letter in let:
print(letter)

For loop Python — Using the original and nested loop

Let's complicate the problem with a list within a list. Let's try to extract the information in separate lines:

  • Let's declare the list_in_list variable and add our list inside the variable;
  • Let's add the original loop with the variable list and list_in_list;
  • In the loop, declare item inside list;
  • Let's call item.
list_in_list = [['one', 'two', 'three'], [25,50,75], [0.25, 0.50, 0.75]]

for list in list_in_list:
for item in list:
print(item)

For loop Python — The result of displaying information from the list

Conclusions

We just looked through:

  • Sequences range();
  • Lists and dictionaries;
  • Nested loops inside the original loop.
Vote:
5 out of 5
Аverage rating : 5
Rated by: 2
1101 CT Amsterdam The Netherlands, Herikerbergweg 292
+31 20 262-58-98
700 300
ITGLOBAL.COM NL
700 300
We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.