logo

Python Numerical Methods

../_images/book_cover.jpg

This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists , the content is also available at Berkeley Python Numerical Methods .

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license . If you find this content useful, please consider supporting the work on Elsevier or Amazon !

< CHAPTER 5. Iteration | Contents | 5.2 While Loops >

For-Loops ¶

A for-loop is a set of instructions that is repeated, or iterated, for every value in a sequence. Sometimes for-loops are referred to as definite loops because they have a predefined begin and end as bounded by the sequence.

The general syntax of a for-loop block is as follows.

CONSTRUCTION : For-loop

A for-loop assigns the looping variable to the first element of the sequence. It executes everything in the code block. Then it assigns the looping variable to the next element of the sequence and executes the code block again. It continues until there are no more elements in the sequence to assign.

TRY IT! What is the sum of every integer from 1 to 3?

WHAT IS HAPPENING?

First, the function range(1, 4) is generating a list of numbers beginning at 1 and ending at 3. Check the description of the function range and get familiar with how to use it. In a very simple form, it is range(start, stop, step) , and the step is optional with 1 as the default.

The variable n is assigned the value 0.

The variable i is assigned the value 1.

The variable n is assigned the value n + i ( \(0 + 1 = 1\) ).

The variable i is assigned the value 2.

The variable n is assigned the value n + i ( \(1 + 2 = 3\) ).

The variable i is assigned the value 3.

The variable n is assigned the value n + i ( \(3 + 3 = 6\) ).

With no more values to assign in the list, the for-loop is terminated with n = 6 .

We present several more examples to give you a sense of how for-loops work. Other examples of sequences that we can iterate over include the elements of a tuple, the characters in a string, and other sequential data types.

EXAMPLE: Print all the characters in the string "banana" .

Alternatively, you could use the index to get each character. But it is not as concise as the previous example. Recall that the length of a string could be determined by using the len function. And we could ignore the start by only giving one number as the stop.

EXAMPLE : Given a list of integers, a , add all the elements of a .

The Python function sum has already been written to handle the previous example. However, assume you wish to add only the even numbers. What would you change to the previous for-loop block to handle this restriction?

NOTE! We use step as 2 in the range function to get the even indexes for list a . Also, a Python shortcut that is commonly used is the operator += . In Python and many other programming languages, a statement like i += 1 is equivalent to i = i + 1 and same is for other operators as -= , *= , /= .

Example Define a dictionary and loop through all the keys and values.

In the above example, we first get all the keys using the method keys , and then use the key to get access the value. Alternatively, we could use the item method in a dictionary, and get the key and value at the same time as show in the following example.

Note that, we could assign two different looping variables at the same time. There are other cases that we could do things similarly. For example, if we have two lists with same length, and we want to loop through them, we could do as the following example using the zip function:

EXAMPLE: Let the function have_digits has the input as a string. The output out should take the value 1 if the string contains digits, and 0 otherwise. You could use the isdigit method of the string to check if the character is a digit.

The first step in the function have_digits assumes that there are no digits in the string s (i.e., the output is 0 or False).

Notice the new keyword break . If executed, the break keyword immediately stops the most immediate for-loop that contains it; that is, if it is contained in a nested for-loop, then it will only stop the innermost for-loop. In this particular case, the break command is executed if we ever find a digit in the string. The code will still function properly without this statement, but since the task is to find out if there are any digit in s , we do not have to keep looking if we find one. Similarly, if a human was given the same task for a long string of characters, that person would not continue looking for digits if he or she already found one. Break statements are used when anything happens in a for-loop that would make you want it to stop early. A less intrusive command is the keyword continue , which skips the remaining code in the current iteration of the for-loop, and continues on to the next element of the looping array. See the following example, that we use the keyword continue to skip the print function to print 2:

EXAMPLE: Let the function my_dist_2_points(xy_points, xy) , where the input argument xy_points is a list of x-y coordinates of a point in Euclidean space, xy is a list that contain an x-y coordinate, and the output d is a list containing the distances from xy to the points contained in each row of xy_points .

Just like if-statements, for-loops can be nested.

EXAMPLE: Let x be a two-dimensional array, [5 6;7 8]. Use a nested for-loop to sum all the elements in x .

s , representing the running total sum, is set to 0.

The outer for-loop begins with looping variable, i, set to 0.

Inner for-loop begins with looping variable, j, set to 0.

s is incremented by x[i,j] = x[0,0] = 5. So s = 5.

Inner for-loop sets j = 1.

s is incremented by x[i,j] = x[0,1] = 6. So s = 11.

Inner for-loop terminates.

Outer for-loop sets i = 1.

s is incremented by x[i,j] = x[1,0] = 7. So s = 18.

s is incremented by x[i,j] = x[1,1] = 8. So s = 26.

Outer for-loop terminates with s = 26.

WARNING! Although possible, do not try to change the looping variable inside of the for-loop. It will make your code very complicated and will likely result in errors.

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python for loops.

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.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Print each fruit in a fruit list:

The for loop does not require an indexing variable to set beforehand.

Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Loop through the letters in the word "banana":

The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Exit the loop when x is "banana":

Exit the loop when x is "banana", but this time the break comes before the print:

Advertisement

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

Do not print banana:

The range() Function

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Using the range() function:

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6) , which means values from 2 to 6 (but not including 6):

Using the start parameter:

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3 ) :

Increment the sequence with 3 (default is 1):

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Print all numbers from 0 to 5, and print a message when the loop has ended:

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Break the loop when x is 3, and see what happens with the else block:

Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Print each adjective for every fruit:

The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.

Test Yourself With Exercises

Loop through the items in the fruits list.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

For Loops in Python – For Loop Syntax Example

Dionysia Lemonaki

While coding in Python, you may need to repeat the same code several times.

Writing the same lines of code again and again repeatedly throughout your program is considered a bad practice in programming – this is where loops come in handy.

With loops, you can execute a sequence of instructions over and over again for a set pre-determined number of times until a specific condition is met.

Using loops in your program will help you save time, minimize errors, and stop repeating yourself.

There are two types of loops in Python:

  • while loops.

In this article, you will learn all about for loops.

If you want to also learn about while loops, you can check out this other article I've written on the topic.

Let's get into it!

What Is a for Loop in Python?

You can use a for loop to iterate over an iterable object a number of times.

An iterable object in Python is any object that can be used as a sequence and looped over.

There are many iterable objects in Python, with some of the most common ones being:

  • dictionaries
  • and strings

The for loop iterates over each item in the sequence in order.

And it executes the same block of code for every item.

Because of this behavior, the for loop is helpful when:

  • You know the number of times you want to execute a block of code.
  • You want to execute the same code for each item in a given sequence.

The main difference between for loops and while loops is that:

  • The for loop carries out the instructions a set number of times.
  • The while loop executes the same action multiple times until a condition is met.

Syntax Breakdown of a for Loop in Python

If you have worked with other programming languages, you will notice that a for loop in Python looks different from for loops in other languages.

For example, in JavaScript, the general syntax of a for loop looks like this:

  • There is an initialization, i = 0 , which acts as the starting point.
  • A condition that needs to be met, i < 5 , for the loop to continue to run.
  • An increment operator, i++ .
  • Curly braces and the body of the for loop that contains the action to take.

A for loop in Python has a shorter, and a more readable and intuitive syntax.

The general syntax for a for loop in Python looks like this:

Let's break it down:

  • To start the for loop, you first have to use the for keyword.
  • The placeholder_variable is an arbitrary variable. It iterates over the sequence and points to each item on each iteration, one after the other. The variable could have almost any name - it doesn't have to have a specific name.
  • Following the placeholder_variable , you then use the in keyword, which tells the placeholder_variable to loop over the elements within the sequence.
  • The sequence can be a Python list, tuple, dictionary, set, string, or any other kind of iterator. Make sure you don't forget the add the colon, : at the end!
  • Next, you add a new line and need to add one level of indentation. One level of indentation in Python is 4 spaces with the spacebar.
  • Lastly, you need to add the body of the for loop. Here you specify the action you want to perform on each item in the sequence.

How to Loop Over a String Using a for Loop in Python

As mentioned earlier, strings are iterable. They are a sequence of characters, meaning you can iterate over them, character by character.

Let's take the following example:

In the example above, I looped over the string Python and printed its individual letters to the console.

You would get the same result if you stored the string in a variable like so:

How to Loop Over a List Using a for Loop in Python

Say you have a list of programming languages and want to iterate through it and print each item in the sequence until you reach the end:

As mentioned earlier, the iterator_variable can be called almost anything – in this case, I named it language .

This language variable refers to each entry in the sequence.

The in keyword, when used with a for loop, indicates that it iterates over every item in the sequence.

On the first iteration of the loop, language points to the first item in the list, Python .

The code statements inside the body of the loop get executed, so the Python gets printed to the console.

On the second iteration, the variable gets updated and points to the second item, JavaScript . It executes the same code statements in the body of the loop.

The same procedure happens for all items in the list until the loop reaches the end and every item has been iterated over.

How to Loop Over a Tuple Using a for Loop in Python

Let's try iterating over all the items inside of a tuple.

As you see, the process for using a for loop with tuples is the same as using a for loop with lists.

How to Loop Over a Dictionary Using a for Loop in Python

Now, let's take a dictionary and iterate over the key-value pairs:

When I use the same syntax I used for strings, lists, tuples, and sets with a dictionary, I end up with only the keys.

To loop over key and value pairs in a dictionary, you need to do what is called tuple unpacking by specifying two variables.

You will also need to use the .items() method to loop over both the keys and values:

But what happens when you don't use the .items() method?

You get a ValueError since Python expects key and value pairs. In Python, keys and values are not separate – they go hand in hand.

How to Write a break Statement in a for Loop in Python

By default, a for loop in Python will loop through the entire iterable object until it reaches the end.

However, there may be times when you want to have more control over the flow of the for loop.

For example, you may want to exit the loop prematurely if a specific condition is met.

To achieve this, you can use the break statement.

In the example above, I want to exit the loop when the variable language points to the list item "Java" .

When Python sees the break keyword, it stops executing the loop, and any code that comes after the statement doesn't run.

As you see from the output of the code, "Java" is printed to the console, and the loop gets terminated.

If you wanted to exit the loop when the variable language points to "Java" but not print the value to the console, then you would write the following:

How to Write a continue Statement in a for Loop in Python

What if you want to skip a particular item?

The continue statement skips the execution of the body of the loop when a condition is met.

In the example above, I wanted to skip "Java" from my list.

I specified that if the language variable points to "Java" , Python should stop and skip the execution at that point and continue to the next item on the list until it reaches the end.

The difference between the break and continue statements is that the break statement ends the loop altogether.

On the other hand, the continue statement stops the current iteration at a specific point and moves on to the next item of the iterable object – it does not exit the loop entirely.

How to Use the range() Function in a for Loop in Python

If you want to loop through a set of code a specified number of times, you can use Python's built-in range() function.

By default, the range() function returns a sequence of numbers starting from 0 , incrementing by one, and ending at a number you specify.

The syntax for this looks like this:

The end argument is required.

Let's see the following example:

In this example, I specified a range(4) .

It means the function will start counting from 0 , increment by 1 on each iteration, and end at 3 .

Keep in mind that the range you specify is not inclusive! So, a range(4) will end at 3 and not 4 .

So, it will include the values of 0 to 3 and not 0 to 4 .

What if you want to iterate through a range of two numbers you specify and don't want to start from 0 ?

You can pass a second optional start argument to specify the starting number.

If you want a range of values from 10 inclusive to 20 inclusive, you write a range of range(10,21) , like so:

Again, range(10,21) does not include 21 .

Lastly, if you don't want the default increment to be 1 , you can specify a third optional parameter, the step parameter.

Something to note is that step can be either a negative or positive number, but it cannot be 0 .

In this example, I wanted to include the values 10 to 20 and increment by 2 .

I achieved this by specifying an increment value of 2 .

Let's take another example.

Say you have a list of items and want to do something to the items that depend on how long the list is.

For that, you could use range() and pass the length of your list as an argument to the function.

To calculate the length of a list, use the len() function.

Hopefully this article helped you understand how to use for loops in Python.

You learned how to write a for loop to iterate over strings, lists, tuples, and dictionaries.

You also saw how to use the break and continue statements to control the flow of the for loop.

Lastly, you saw how to specify a range of numbers to use in your for loop with the range() function.

Thank you for reading, and happy coding!

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Using multiple variables in a For loop in Python

avatar

Last updated: Apr 10, 2024 Reading time · 5 min

banner

# Table of Contents

  • Declare as many variables as there are items in each tuple
  • Using multiple variables in a For loop with two-dimensional list
  • Using multiple variables in a For loop using dict.items()
  • Using multiple variables in a For loop using enumerate()
  • Using 2 variables in a For loop to simulate a nested loop

# Using multiple variables in a For loop in Python

To use multiple variables in a for loop:

  • Use the zip function to group multiple iterables into tuples.
  • Use a for loop to iterate over the zip object.
  • Unpack the items of each tuple into variables.

using multiple variables in for loop

The zip() function iterates over several iterables in parallel and produces tuples with an item from each iterable.

The zip function returns an iterator of tuples.

# Declare as many variables as there are items in each tuple

Make sure to declare exactly as many variables as there are items in each tuple.

declare as many variables as there are items in each tuple

If you try to unpack more or fewer variables than there are items in each tuple, you'd get an error.

# Using multiple variables in a For loop with two-dimensional list

Here is an example of unpacking variables in a for loop when iterating over a two-dimensional list.

using multiple variables in for loop with two dimensional list

The first variable gets assigned the first element of the nested list of the current iteration and the second variable gets assigned the second element.

When you use unpacking, you have to make sure to unpack exactly as many variables as there are values in the iterable, otherwise an error is raised.

Here is an example that doesn't unpack the values of each tuple.

If not all nested sequences have the same length, access each sequence at an index.

The last sublist has more items than the previous two, so unpacking is not an option.

If you need to iterate over the key-value pairs of a dictionary in a for loop, use the dict.items() method.

# Using multiple variables in a For loop using dict.items()

This is a three-step process:

  • Use the dict.items() method to get a view of the dictionary's items.
  • Use a for loop to iterate over the view object.
  • Unpack the key and value into variables.

using multiple variables in for loop using dict items

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

On each iteration of the for loop, we unpack the current key and value into variables.

If you need to get access to the index of the current iteration in a for loop, use the enumerate() function.

# Using multiple variables in a For loop using enumerate()

  • Use the enumerate() function to get access to the current index.
  • Use a for loop to iterate over the enumerate object
  • Unpack the current item and index into variables.

using multiple variables in for loop with enumerate

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

On each iteration of the for loop, we unpack the current index and item into variables.

# Using 2 variables in a For loop to simulate a nested loop

If you need to use 2 variables in a for loop to simulate a nested for loop, use the itertools.product() class.

using 2 variables in for loop to simulate nested loop

The itertools.product() method is roughly equivalent to a nested for loop.

For each item in list_1 , the for loop iterates over each item in list_2 .

Here is an example of a nested for loop that achieves the same result.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • For or While loop to print Numbers from 1 to 10 in Python
  • Using a For or While Loop to take user input in Python
  • Detect the Last item in a List using a for loop in Python
  • Python: Declaring a Variable without assigning it a Value

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Python Programming

Python for loop

Updated on:  December 28, 2022 | 36 Comments

In this article, you’ll learn ‎what is for loop in Python and how to write it. We use a for loop when we want to repeat a code block a fixed number of times.

A for loop is a part of a  control flow statement which helps you to understand the basics of Python .

Also, Solve :

  • Python loop Exercise
  • Python loop Quiz

Table of contents

  • Example: Print first 10 numbers using a for loop

for loop with range()

How for loop works, why use for loop, if-else in for loop, break for loop, continue statement in for loop, pass statement in for loop, else block in for loop, backward iteration using the reversed() function, reverse for loop using range(), while loop inside for loop, for loop in one line, accessing the index in for loop, iterate string using for loop, iterate list using for loop, iterate dictionary using for loop, what is for loop in python.

In Python, the for loop is used to iterate over a sequence such as a list , string, tuple , other iterable objects such as range .

With the help of for loop, we can iterate over each item present in the sequence and executes the same set of operations for each item. Using a for loops in Python we can automate and repeat tasks in an efficient manner.

So the bottom line is using the for loop we can repeat the block of statements a fixed number of times. Let’s understand this with an example.

As opposed to while loops that execute until a condition is true, for loops are executed a fixed number of times, you need to know how many times to repeat the code.

  • An unknown number of times : For example, Ask the user to guess the lucky number. You don’t know how many attempts the user will need to guess correctly. It can be 1, 20, or maybe indefinite. In such cases, use a while loop.
  • Fixed number of times : Print the multiplication table of 2. In this case, you know how many iterations you need. Here you need 10 iterations. In such a case use for loop.

for loop in Python

Syntax of for loop

  • In the syntax, i is the iterating variable, and the range specifies how many times the loop should run. For example, if a list contains 10 numbers then for loop will execute 10 times to print each number.
  • In each iteration of the loop, the variable i get the current value.

Example : Print first 10 numbers using a for loop

  • Here we used the range() function to generate integers from 0 to 9
  • Next, we used the for loop to iterate over the numbers produced by the range() function
  • In the body of a loop, we printed the current number.

The range() function returns a sequence of numbers starting from 0 (by default) if the initial limit is not specified and it increments by 1 (by default) until a final limit is reached.

The range() function is used with a loop to specify the range (how many times) the code block will be executed. Let us see with an example.

for loop with range()

Example: Print sum of all even numbers from 10 to 20

  • Set sum variable to zero.
  • Use the range(2, 22, 2) to get all even numbers from 2 to 20. (Here a step value is 2 to get the even number because even numbers are divisible by 2)
  • Next, use for loop to iterate over each number
  • In each iteration add the current number to the sum variable using the arithmetic operator .

The for loop is the easiest way to perform the same actions repeatedly. For example, you want to calculate the square of each number present in the list .

Write for loop to iterate a list, In each iteration, it will get the next number from a list, and inside the body of a loop, you can write the code to calculate the square of the current number.

Example: Calculate the square of each number of list

Python list is an ordered sequence of items. Assume you have a list of 10 numbers. Let’s see how to want to calculate the square of each number using for loop.

The loop runs till it reaches the last element in the sequence. If it reaches the last element in the sequence, it exits the loop. otherwise, it keeps on executing the statements present under the loop’s body

Flow char of a for loop

Let’s see the use for loop in Python.

  • Definite Iteration : When we know how many times we wanted to run a loop, then we use count-controlled loops such as for loops. It is also known as definite iteration. For example, Calculate the percentage of 50 students. here we know we need to iterate a loop 50 times (1 iteration for each student).
  • Reduces the code’s complexity : Loop repeats a specific block of code a fixed number of times. It reduces the repetition of lines of code, thus reducing the complexity of the code. Using for loops and while loops we can automate and repeat tasks in an efficient manner.
  • Loop through sequences : used for iterating over lists, strings, tuples, dictionaries , etc., and perform various operations on it, based on the conditions specified by the user.

Example: Calculate the average of list of numbers

In this section, we will see how to use if-else statements with a loop. If-else is used when conditional iteration is needed. For example, print student names who got more than 80 percent.

The if-else statement checks the condition and if the condition is True it executes the block of code present inside the if block and if the condition is False, it will execute the block of code present inside the else block.

When the if-else condition is used inside the loop, the interpreter checks the if condition in each iteration, and the correct block gets executed depending on the result.

Example : Print all even and odd numbers

  • In this program, for loop statement first iterates all the elements from 0 to 20.
  • Next, The if statement checks whether the current number is even or not. If yes, it prints it. Else, the else block gets executed.

Practice Problem : –

Use for loop to generate a list of numbers from 9 to 50 divisible by 2.

Loop Control Statements in for loop

Loop control statements change the normal flow of execution. It is used when you want to exit a loop or skip a part of the loop based on the given condition. It also knows as transfer statements.

Now, let us learn about the three types of loop control statements i.e., break , continue and pass .

The break statement is used to terminate the loop . You can use the break statement whenever you want to stop the loop. Just you need to type the break inside the loop after the statement, after which you want to break the loop.

When the break statement is encountered, Python stops the current loop, and the control flow is transferred to the following line of code immediately following the loop.

Example: break the loop if number a number is greater than 15

  • In this program, for loop iterates over each number from a list.
  • Next, the if statement checks if the current is greater than 15. If yes, then break the loop else print the current number

Note : If the break statement is used inside a nested loop (loop inside another loop), it will terminate the innermost loop.

The continue statement skips the current iteration of a loop and immediately jumps to the next iteration

Use the continue statement when you want to jump to the next iteration of the loop immediately. In simple terms, when the interpreter found the continue statement inside the loop, it skips the remaining code and moves to the next iteration.

The continue statement skips a block of code in the loop for the current iteration only. It doesn’t terminate the loop but continues in the next iteration ignoring the specified block of code. Let us see the usage of the continue statement with an example.

Example: Count the total number of ‘m’ in a given string.

  • In this program, the for loop statement iterates over each letter of a given string.
  • Next, the if statement checks the current character is m or not. If it is not m, it continues to the next iteration to check the following letter. else it increments the count

Note : In the case of an inner loop, it continues the inner loop only.

The pass statement is a null statement, i.e., nothing happens when the statement is executed. Primarily it is used in empty functions or classes. When the interpreter finds a pass statement in the program, it returns no operation.

Sometimes there is a situation in programming where we need to define a syntactically empty block. We can define that block with the pass keyword.

Let us see the usage of the pass statement with an example.

Same as the if statement, Python allows us to use an else statement along with for loop. In Python, for-loop can have the else block, which will be executed when the loop terminates normally . Defining the else part with for loop is optional.

else block will be skipped when

  • for loop terminate abruptly
  • the break statement is used to break the loop

Example 1: Else block in for loop

In this example, we are printing the first 5 numbers, and after successful execution of a loop, the interpreter will execute the else block.

Example 2: Both break and else statement

In this example, We are printing print only the first two numbers out of 5, and after that, we use the break statement to stop the loop. Because the loop is terminated abruptly, the else block will not execute.

Reverse for loop

Till now, we have learned about forward looping in for loop with various examples. Now we will learn about the backward iteration of a loop.

Sometimes we require to do reverse looping, which is quite useful. For example, to reverse a list.

There are three ways to iterating the for loop backward

  • Reverse for loop using the reversed() function

We can use the built-in function reversed() with for loop to change the order of elements, and this is the simplest way to perform a reverse looping.

We can use the built-in function  range()  with the for loop to reverse the elements’ order. The  range()  generates the integer numbers between the given start integer to the stop integer.

Example 3: Reverse a list using a loop

Nested for loops

Nested for loop is a for loop inside another for a loop.

A nested loop has one loop inside of another. It is mainly used with two-dimensional arrays. For example, printing numbers or star patterns. Here outer loop is nothing but a row, and the inner loop is columns.

In nested loops, the inner loop finishes all of its iteration for each iteration of the outer loop. i.e., For each iteration of the outer loop inner loop restart and completes all its iterations, then the next iteration of the outer loop begins.

Syntax of nested for loops :

Example : Nested for loop to print the following pattern

Nested for loop

  • In this program, the outer loop is the number of rows print. 
  • The number of rows is five, so the outer loop will execute five times
  • Next, the inner loop is the total number of columns in each row.
  • For each iteration of the outer loop, the columns count gets incremented by 1
  • In the first iteration of the outer loop, the column count is 1, in the next it 2. and so on.
  • The inner loop iteration is equal to the count of columns.
  • In each iteration of an inner loop, we print star

The while loop is an entry-controlled loop, and a for loop is a count-controlled loop. We can also use a while loop under the for loop statement. Let us see an example to understand better.

Example: Print Multiplication table of a first 5 numbers using for loop and while loop

  • In this program, we iterate the first five numbers one by one using the outer loop and range function
  • Next, in each iteration of the outer loop, we will use the inner while loop to print the multiplication table of the current number

We can also formulate the for loop statement in one line to reduce the number of lines of code. Let us see an example of it.

Example: Print the even numbers by adding 1 to the odd numbers in the list

The enumerate() function is useful when we wanted to access both value and its index number or any sequence such as list or string. For example, a list is an ordered data structure that stores each item with its index number. Using the item’s index number, we can access or modify its value.

Using enumerate function with a loop, we can access the list’s items with their index number. The enumerate() adds a counter to iteration and returns it in the form of an enumerable object.

There three ways to access the index in for loop let’s see each one by one

Example 1: Print elements of the list with its index number using the enumerate() function

In this program, the for loop iterates through the list and displays the elements along with its index number.

Example 2: Printing the elements of the list with its index number using the range() function

By looping through the string using for loop, we can do lots of string operations. Let’s see how to perform various string operations using a for loop.

Example 1: Access all characters of a string

Example 2: Iterate string in reverse order

Example 3: Iterate over a particular set of characters in string

Example 5: Iterate over words in a sentence using the split() function.

First, let us learn what a list is. Python list is an ordered collection of items of different data types. It means Lists are ordered by index numbers starting from 0 to the total items-1. List items are enclosed in square [] brackets.

Below are the few examples of Python list.

Using a loop, we can perform various operations on the list. There are ways to iterate through elements in it. Here are some examples to help you understand better.

Example 1: Iterate over a list

Example 2: Iterate over a list using a for loop and range .

Example 3: list comprehension

First, let us learn what a dictionary is. Python dictionary is used to store the items in the format of key-value pair. It doesn’t allow duplicate items. It is enclosed with {}. Here are some of the examples of dictionaries.

There are ways to iterate through key-value pairs. Here are some examples to help you understand better.

Example 1: Access only the keys of the dictionary.

Example 2: Iterate keys and values of the dictionary

Example 5: Iterate only the values the dictionary

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

variable assignment in for loop python

I’m  Vishal Hule , the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on  Twitter .

Related Tutorial Topics:

Python exercises and quizzes.

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Loading comments... Please wait.

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills .

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

To get New Python Tutorials, Exercises, and Quizzes

Legal Stuff

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use , Cookie Policy , and Privacy Policy .

Copyright © 2018–2024 pynative.com

youtube logo

How to Dynamically Declare Variables Inside a Loop in Python

By Naveenkumar M" on 2021-07-18

image

Declaring variables is always a hectic task for programmers. And as the program increases in size, the pain increases too. At the beginning of the code, we try to declare variables with a valid name like temp, hashedKey, and likewise. But as time goes on, our code will be huge and we will be exhausted of the thinking capacity to find a suitable variable name. Then we name them x, y, and so on.

The problem becomes more complicated when you need to declare variables dynamically in a loop. I came up with three ways to do this in Python.

1. Using the exec command

image

In the above program, I initially declared an empty dictionary and added the elements into the dictionary. I used string concatenation method to declare dynamic variables like x1, x2, x3……. . Then I assumed the values from the for loop to the dynamic variables. The dictionary will look like

{‘x0’: 0, ‘x1’: 1, ‘x2’: 2, ‘x3’: 3, ‘x4’: 4, ‘x5’: 5, ‘x6’: 6, ‘x7’: 7, ‘x8’: 8, ‘x9’: 9}

You can learn about dictionaries here. Python Dictionaries

Finally, I iterated over the dictionary and separated the keys into a standalone variable using the exec command. The exec command executes the Python code inside it. exec( f ‘ {key}={value}’) — here f represents the string format.

image

Now you can check the global variables using the above code and you can see that the dictionary keys are now copied as standalone global variables. The output will be like this. You can clearly see that there are 10 variables declared starting from x0 to x9.

image

Note: The dictionary remains unchanged.

2. Using globals()

globals() function in Python returns the dictionary of the current global symbol table. It requires no params. It also returns the global variables declared inside a program.

You can learn about globals() here .

image

globals() is a dictionary which contains all the global variables with the variable name as its key and value as its value. Declaring variables using globals is the same as declaration using a dictionary. The output is the same as the first one.

3. Using OOP

One of the greatest features of Python is its support for OOP (Object-Oriented Programming). We shall get to the use of that amazing property to declare variables dynamically.

image

I think most of you are familiar with classes and the zip method. But for those who have not explored it, you can learn from here. Python zip() Python Oops Concept

In the above code, I have dynamically declared the attributes of an object instead of declaring it as a global variable. The set attribute is a class method which enables us to declare new attributes to an object after it has been initialized and not for the whole class.

You can check the attributes of the object using the below command.

image

Thanks to everyone who contributed to this article. How can you dynamically create variables via a while loop?

Thank you everyone for reading.

If you want me to post any other articles on any topic, feel free to ping me on WhatsApp +91 8870499146.

Continue Learning

The mysteries of floating-point numbers.

Exploring the Fascinating World of Computational Precision

How to Send Mail Using Python

Introduction to Simple Mail Transfer Protocol in Python

Search for Text in a PDF with Python

Nobody likes working with PDFs, but we have to

An Introduction to Prim's Algorithm in Python

Use Prim's Algorithm to find the Minimum Spanning Tree of an undirected graph.

How to Validate Your DataFrames with Pytest

A guide to validating DataFrames with Pytest.

Install Python on a Locked-Down PC Without Local Admin

Even if you don't have local admin or if you are not able to run installers to install software on your PC, you can still use Python.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Changing Variable Names With Python For Loops

  • Python | Assign multiple variables with list values
  • Python Dictionary with For Loop
  • Loops in Python - For, While and Nested Loops
  • Global and Local Variables in Python
  • Convert String into Variable Name in Python
  • Get Variable Name As String In Python
  • Python | Unpack whole list into variables
  • Changing Class Members in Python
  • Unused variable in for loop in Python
  • Assigning multiple variables in one line in Python
  • How To Print A Variable's Name In Python
  • Write Multiple Variables to a File using Python
  • Python - Replace Non-None with K
  • How to Write Memory Efficient Loops in Python
  • Assign Function to a Variable in Python
  • Viewing all defined variables in Python
  • Python: Map VS For Loop
  • Print Single and Multiple variable in Python
  • 3 Rookie Mistakes to Avoid with Python Lists

When we write variable names play a crucial role in code readability and maintainability. However, there are situations where you might need to change variable names systematically, perhaps to adhere to a naming convention, improve clarity, or for any other reason. In Python, the flexibility of for loops allows you to automate the process of changing variable names. In this article, we will explore various techniques to change variable names using loops.

Below, are the methods of Changing Variable Names With Python For Loops

  • Adding Prefix with Variable Name
  • Adding Suffix with Variable Name
  • Change Character Case
  • Replace Character

Changing Variable Names With Python Using Prefix

In this example, below Python code below adds the prefix “ var_ ” to each variable name in the list original_names . It uses a for loop to iterate through the original names, creates new names with the prefix, and appends them to the list prefixed_names . Finally, it prints both the original and prefixed names for reference.

Changing Variable Names With Python Using Suffix

In this example, below Python code adds a suffix “ _new ” to each variable name in the list original_names . It utilizes a for loop to iterate through the original names, creates new names with the suffix, and appends them to the list suffixed_names .

Changing Variable Names With Python by Change Character Case

In this example, below Python code changes the case of variable names in the list original_names to lowercase. Using a for loop, it iterates through the original names, converts each name to lowercase, and appends the result to the list lowercase_names .

Changing Variable Names With Python by Replace Character

In this example below, Python code replaces underscores with hyphens in variable names within the list ` original_names `. Using a for loop, it iterates through the original names, performs the replacement, and appends the modified names to the list ` replaced_names `.

Please Login to comment...

Similar reads.

  • python-basics
  • Python Programs

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to Use a for Loop for Multiple Variables in Python

  • Python How-To's
  • How to Use a for Loop for Multiple …

Use the for Loop With the items() Method for Multiple Assignments in a Dictionary in Python

Use the for loop with the enumerate() function for multiple assignments in a list in python, use the for loop with the zip() function for multiple assignments in a tuple or list in python, use the for loop with the range() function for multiple assignments in a list in python, use nested for loops for multiple assignments in a list in python.

How to Use a for Loop for Multiple Variables in Python

A for loop is a fundamental control flow structure in Python, essential for iterating over various sequences such as lists, tuples, dictionaries, and even strings. This article focuses on the use of the for loop to handle multiple variables in Python.

Dictionaries serve as a versatile data structure in Python, enabling the storage of data values in key-value pairs. In simple terms, a dictionary maps one value to another, analogous to how an English dictionary maps a word to its definition.

To achieve multiple assignments within a dictionary using a for loop, the items() method is employed on the given Python dictionary. This provides the output as a list containing all the dictionary keys along with their corresponding values.

The general syntax for the items() method is:

Here, dictionary is the dictionary for which you want to retrieve key-value pairs. The items() method returns a view object that can be used to iterate over the dictionary’s key-value pairs as tuples.

Let’s take a closer look at the following code:

In this example, the items() method is used to retrieve the key-value pairs from the dict1 dictionary. The for loop iterates over these pairs, allowing you to access and print each key and its corresponding value.

The enumerate() function in Python is used to add a counter to an iterable and return it as an enumerate object. This proves especially useful when dealing with multiple lists, allowing for concurrent processing using indexes to access corresponding elements in the other list.

The general syntax for the enumerate() function is as follows:

Parameters:

iterable : This is the iterable (list, tuple, string, etc.) for which you want to generate an enumerate object. It can be any iterable object where you want to access both the elements and their indices.

start (optional): This parameter specifies the starting value of the index. By default, it starts from 0, but you can provide any integer value to start the index from a different number.

The enumerate() function returns an enumerate object, which is an iterator that yields tuples containing an index and an element from the given iterable.

The following code snippet illustrates the use of the enumerate() function for multiple assignments within a list:

In this code, two lists, namely coins and prices , are simultaneously manipulated through assignment operations.

The enumerate() object facilitates this process by providing the necessary indexes, enabling the efficient traversal of both lists concurrently.

The zip() function, a built-in feature in Python’s toolkit, is used to aggregate elements from multiple iterables (lists, tuples, etc.) into an iterator of tuples.

The general syntax for the zip() function is as follows:

*iterables : This is the variable-length argument list. You can pass multiple iterables (lists, tuples, etc.) as separate arguments to the zip() function.

It accepts any number of iterables, and elements from each iterable will be paired together.

The zip() function returns an iterator of tuples where each tuple contains the corresponding elements from the input iterables.

This function not only enables parallel interaction but also supports the simultaneous unpacking of multiple variables.

The code snippet below demonstrates the use of the zip() function for multiple assignments within a tuple or list.

In this example, the zip() function accepts two lists as parameters and generates an iterable. This iterable yields tuples that comprise corresponding elements from the given lists, presenting them as the loop iterates over it.

This significantly streamlines the handling of multiple variables within a loop. The output obtained shows the merging of elements from both lists.

One of the distinct advantages of zip() is its ability to work with iterables of unequal lengths. When the iterables provided to zip() differ in length, the resulting iterable will have the length of the shortest iterable.

This ensures that you can process and handle data from multiple sources even when their lengths aren’t identical.

Handling multiple variables in Python can also be done using the range() function with the len() function. This allows for a structured traversal of multiple iterables, especially when accessing elements through their indices is necessary.

The general syntax for the range() function is as follows:

start (optional): This parameter specifies the starting value of the range (inclusive). If omitted, the default value is 0.

stop : This parameter specifies the ending value of the range (exclusive). The range() function will generate numbers up to, but not including, this value.

step (optional): This parameter specifies the increment between each number in the range. If omitted, the default value is 1.

The range() function, paired with len() , can generate a sequence of indices that correspond to the position of elements within the iterables.

In the code snippet below, we have two lists: list1 containing numeric values [1, 2, 3] and list2 containing corresponding alphabetic characters ['a', 'b', 'c'] . The objective here is to pair each element from list1 with its corresponding element from list2 using their respective indices.

Take a look at the example:

In this specific example, the for loop iterates through the indices generated by range(len(list1)) . This approach enables access to elements in both list1 and list2 by using the corresponding index.

For each iteration, the i variable holds the current index, and item1 and item2 are assigned the elements from list1 and list2 at that index, respectively. Consequently, this method facilitates a pairing of elements, assuming the iterables are of the same length.

The code output shows the successful pairing of elements from both list1 and list2 .

Nested for loops in Python provide a versatile approach to dealing with multiple variables in a structured and organized way. This allows you to navigate through several iterables, performing operations based on their positions or interrelationships.

In the provided code example, two lists, list1 and list2 , are used to demonstrate the usage of nested for loops. list1 contains numerical values [1, 2, 3] , while list2 consists of corresponding alphabetic characters ['a', 'b', 'c'] .

The goal is to systematically pair each element from list1 with every element from list2 .

See the code example:

The outer loop, represented by for item1 in list1: , takes each element from list1 and initiates the inner loop. The inner loop, represented by for item2 in list2: , then traverses through list2 , systematically pairing each element from list1 with all elements from list2 .

We can see that the output of this code illustrates the pairing of the elements from both lists.

Using multiple variables within a for loop in Python is a valuable technique that can be applied effectively to lists or dictionaries. However, it’s important to note that it’s not a general-purpose approach and requires caution.

This technique, known as iterable unpacking, involves assigning multiple variables simultaneously in a single line of code.

Using the methods discussed above, you can effectively utilize for loops to handle multiple variables in Python. Whether you need to access elements based on indices or traverse iterables in a nested fashion, these techniques provide the flexibility and control needed to work with multiple variables seamlessly.

Vaibhhav Khetarpal avatar

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article - Python Loop

  • How to Access the Index in 'Foreach' Loops in Python
  • How to Get User Input in Python While Loop
  • How to Get The Next Item in Python for Loop
  • Async for Loop in Python
  • How to Retry a Loop in Python
  • How to Skip Iterations in a Python Loop

For Loop with Two Variables in Python

For Loop With 2 Variables

Python  is a high-level, general-purpose programming language. Python was created by Guido van Rossum and was first released on  February 20, 1991 . It is a widely used and easy language to learn. It has simplified syntax, which gives more emphasis on natural language. You can quickly write and execute the code in Python faster than in other languages.

Here we will learn about the for loop and how to loop through with the two variables. “for” loop is widely used and easy to implement. For loop is used to perform an iteration over the sequence.

Before diving into the topic, one should install Python in the system.

Check for Python Version

Python is already installed in the system. To check if it’s installed, open  cmd/terminal  and type python – -version

Python Version

If you get the version then you are good to go. Else, you can refer here for the Python Installation . We need python in our system to run python codes.

What is a Loop ?

Loops help you to execute a block of code repeatedly until the condition is met. There are three types of loops in python:

  • For Loop : It is used to iterate over a sequence like a list, tuple, set, dictionary, or string.
  • While Loop : It executes till the condition is True .
  • Nested Loop : Loops can be nested which means a loop inside the other loop’s body. For example: for loop inside a for loop, while loop inside the for loop, and so on.

You can refer to Python Loops for more details.

For Loop In Python

As we learned above a for loop is used to iterate over a sequence like a list, tuple, set, dictionary, or string. “for” is a reserved iteration keyword used for creating a “ for ” loop just like while .

Syntax of for loop:

  • “ for ” is a keyword reserved for loop
  • element is a variable name of a single item during iteration.
  • “ in ” is a reserved keyword used to check the value present in the sequence while the iteration
  • “ : ” colon is the indication that now the body starts
  • then, the body of the for loop followed by 4 spaces(tab) for the indentation

Let’s look at the simple example of how the for loop works with one variable.

“ for ” Loop with One Variable

Here is the for loop following the general syntax which is mentioned above. This is the most basic and easy example to understand how the loop runs through the list of languages.

  • assigned a list of languages(C, Python, Java, JavaScript, Go) to the variable languages
  • as following the syntax started the loop with the keyword “ for “
  • “ language ” is the arbitrary variable that represents a single element in the list of languages
  • “languages” is the list
  • lastly, we are printing the single element of the list one by one.

For Loop One Variable

Now let’s move on to the topic we are here for which is looping through for loop using two variables.

“ for ” Loop with Two Variables

Syntax changes a little bit here as we are using two variables as we have learned above.

This syntax basically we can use over lists, and dictionaries else we might get errors. Let’s take a look in detail.

Example 1: Looping through Dictionary

A dictionary is used to store the data in the key: value pair. In the dictionary, we have items() method. It returns a list containing a tuple for each key-value pair. When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the  items()  method.

In this piece of code, we have assigned the dictionary which contains key and value pairs to a person variable. We are looping through both  keys  and  values , by using the  items()  function. Each repetition will provide you with both the key and value of each item.

For Loop Dictionary Two Variable

  • 6 is the value of the Dhushi key
  • 32 is the value of the Lee key
  • 30 is the value of the Marc key

You may check: How to Initialize Dictionary in Python – A Step-By-Step Guide .

Example 2: “ for ” Loop using enumerate() function

enumerate() the function is used to retrieve the position index and corresponding value while looping through the list. Let’s take a look at the code.

  • In the languages variable, we are assigning a list of values
  • as following the syntax started the loop with the keyword “ for
  • here we are using two arbitrary variable index and value

For Loop Enumerate Function

As an output, we are printing the index variable which contains the index value(starting from 0), and the value variable contains the values of the list.

Example 3: “ for ” Loop using zip() function

To loop over two or more sequences at the same time, the entries can be paired with the zip()  function.

  • here we are looping through sequences which are lists stored in variable names and languages
  • the two variables used for the loops are name and language which will be storing the values of names and languages

For Loop Zip Function

In the output, we are getting the name from the first list and the language from the second list. Another way to think of  zip()  is that it turns rows into columns and columns into rows

In this article, we learned about the for loop and how to loop through using two variables. For loop is basically used for iterations to check certain conditions and execute it till it met the condition. For loop could be used with one arbitrary variable or even two as we have studied above. There are functions like enumerate() , and zip() which could be used with 2 variables for iteration.

You can refer to the Python Documentation for more information and learn about different topics.

20. For Loops

By Bernd Klein . Last modified: 08 Nov 2023.

On this page ➤

Introduction

Thinking of a for loop

A for loop in Python is used for iterating over a sequence (such as a list, tuple, string, or range) or other iterable objects. It's a fundamental control structure in programming that allows you to repeat a block of code a specific number of times or iterate through the elements of a sequence.

So what about the while loop? Do we need another kind of a loop in Python? Can we not do everything with the while loop? Yes, we can rewrite 'for' loops as 'while' loops. But before we go on, you want to see at least one example of a for loop.

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Syntax of the For Loop

As we mentioned earlier, the Python for loop is an iterator based for loop. It steps through the items of lists, tuples, strings, the keys of dictionaries and other iterables. The Python for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through. The general syntax looks like this:

A first example of a for loop:

The for loop is used to go through each element in the performance_levels tuple one by one. In each iteration, the loop variable level will take on the value of the current element in the tuple.

Inside the loop, the print() function is used to display the current value of the level variable. This means that it will print each performance level to the screen, starting with "beginner," then "novice," and so on, until it reaches "expert."

The loop will continue to iterate until it has gone through all the elements in the performance_levels tuple.

To summarize:

The items of the sequence object are assigned one after the other to the loop variable; to be precise the variable points to the items. For each item the loop body is executed.

We mentioned before that we can rewrite a for loop as a while statement. In this case it looks like this:

We can easily see that the for loop is more elegant and less error prone in this case.

Different Kinds of for Loops

If you are beginner in programming, you can or maybe you should even skip this subchapter, in which we will talk about different ways implementations of for loops in other programming languages.

There are hardly any programming languages without for loops, but the for loop exists in many different flavours, i.e. both the syntax and the semantics differs from one programming language to another.

Different kinds of for loops:

Count-controlled for loop (Three-expression for loop)

This is by far the most common type. This statement is the one used by C. The header of this kind of for loop consists of a three-parameter loop control expression. Generally it has the form: for (A; Z; I) A is the initialisation part, Z determines a termination expression and I is the counting expression, where the loop variable is incremented or dcremented. An example of this kind of loop is the for-loop of the programming language C: for (i=0; i <= n; i++) This kind of for loop is not implemented in Python!

Numeric Ranges

This kind of for loop is a simplification of the previous kind. It's a counting or enumerating loop. Starting with a start value and counting up to an end value, like for i = 1 to 100 Python doesn't use this either.

Vectorized for loops

They behave as if all iterations are executed in parallel. That is, for example, all expressions on the right side of assignment statements get evaluated before the assignments.

Iterator-based for loop

Finally, we come to the one used by Python. This kind of for loop iterates over an enumeration of a set of items. It is usually characterized by the use of an implicit or explicit iterator. In each iteration step a loop variable is set to a value in a sequence or other data collection. This kind of for loop is known in most Unix and Linux shells and it is the one which is implemented in Python.

Upcoming online Courses

More about the Python for Loop

Another Example of a simple for loop in Python. We will also use this example in the following:

Can of Spam

The else block is special; while Perl programmer are familiar with it, it's an unknown concept to C and C++ programmers. Semantically, it works exactly as the optional else of a while loop. It will be executed only if the loop hasn't been "broken" by a break statement. So it will only be executed, after all the items of the sequence in the header have been used.

If a break statement has to be executed in the program flow of the for loop, the loop will be exited and the program flow will continue with the first statement following the for loop, if there is any at all. Usually break statements are wrapped into conditional statements, e.g.

Removing "spam" from our list of edibles, we will gain the following output:

Maybe, our disgust with spam is not so high that we want to stop consuming the other food. Now, this calls the continue statement into play . In the following little script, we use the continue statement to go on with our list of edibles, when we have encountered a spam item. So continue prevents us from eating spam!

The range() Function

The built-in function range() is the right function to iterate over a sequence of numbers. It generates an iterator of arithmetic progressions: Example:

This result is not self-explanatory. It is an object which is capable of producing the numbers from 0 to 4. We can use it in a for loop and you will see what is meant by this:

range(n) generates an iterator to progress the integer numbers starting with 0 and ending with (n -1). To produce the list with these numbers, we have to cast range() with the list(), as we do in the following example.

range() can also be called with two arguments:

The above call produces the list iterator of numbers starting with begin (inclusive) and ending with one less than the number end .

So far the increment of range() has been 1. We can specify a different increment with a third argument. The increment is called the step . It can be both negative and positive, but not zero:

Example with step:

It can be done backwards as well:

The range() function is especially useful in combination with the for loop, as we can see in the following example. The range() function supplies the numbers from 1 to 100 for the for loop to calculate the sum of these numbers:

Calculation of the Pythagorean Numbers

Pythagorean Theorem Proof

Generally, it is assumed that the Pythagorean theorem was discovered by Pythagoras that is why it has his name. However, there is a debate whether the Pythagorean theorem might have been discovered earlier or by others independently. For the Pythagoreans, - a mystical movement, based on mathematics, religion and philosophy, - the integer numbers satisfying the theorem were special numbers, which had been sacred to them.

These days Pythagorean numbers are not mystical anymore. Though to some pupils at school or other people, who are not on good terms with mathematics, they may still appear so.

So the definition is very simple: Three integers satisfying a2+b2=c2 are called Pythagorean numbers.

The following program calculates all pythagorean numbers less than a maximal number. Remark: We have to import the math module to be able to calculate the square root of a number.

Iterating over Lists with range()

If you have to access the indices of a list, it doesn't seem to be a good idea to use the for loop to iterate over the lists. We can access all the elements, but the index of an element is not available. However, there is a way to access both the index of an element and the element itself. The solution lies in using range() in combination with the length function len():

Remark: If you apply len() to a list or a tuple, you get the number of elements of this sequence.

List iteration with Side Effects

If you loop over a list, it's best to avoid changing the list in the loop body. Take a look at the following example:

To avoid these side effects, it's best to work on a copy by using the slicing operator, as can be seen in the next example:

We still might have done something, we shouldn't have done. We changed the list "colours", but our change didn't have any effect on the loop. The elements to be looped remained the same during the iterations.

Exercises with for Loops

Exercise 1: fibonacci numbers.

Generate and print the first n numbers in the Fibonacci sequence using a for loop.

Exercise 2: Diamond Pattern

Create a program that prints a diamond pattern using asterisks (*) like the example below:

Exercise 3: Prime Numbers

Write a program to find and print all prime numbers between 1 and 50 using a for loop.

Exercise 4: Fizz, Buzz, FizzBuzz

Print numbers from 1 to 42, but for multiples of 3, print "Fizz," and for multiples of 5, print "Buzz." For numbers that are multiples of both 3 and 5, print "FizzBuzz."

Exercise 5: Ramanujan-Hardy number

This exercise is about the Ramanujan-Hardy number. There is a little anecdote of the Mathematician G.H. Hardy when he visited Indian mathematician Srinivasa Ramanujan in hospital. It goes like this:

For this reason 1732 is known as the Ramanujan-Hardy number.

Can you verify this with a Python program?

Exercise 6:

1729 is the lowest number which can be represented by a Loeschian quadratic form $a^2 + ab + b^2$ in four different ways, with positive integers a and b .

Exercise 7: Pascal's Trianlge

Write a Python program to generate and print the first n rows of Pascal's Triangle. Pascal's Triangle is a mathematical pattern of numbers where each number is the sum of the two numbers directly above it. The first few rows of Pascal's Triangle look like this:

Your program should take an integer n as input and print the first n rows of Pascal's Triangle. You'll need to use nested for loops to calculate and print each row.

This exercise can be quite challenging, but it's a great way to practice nested loops and pattern generation in Python.

Solution to Exercise 1

Solution to exercise 2, solution to exercise 3, solution to exercise 4, solution to exercise 5, solution to exercise 6, solution to exercise 7.

On this page

How to Write a For Loop in Python

Author's photo

  • learn python
  • online practice

The for loop is one of the basic tools in Python. You will likely encounter them at the very beginning of your Python journey. In this article, I’ll give you a brief overview of the for loop in Python and demonstrate with examples how you can use it to iterate over different types of sequences.

What Is a For Loop in Python?

Python is a powerful programming language that can be used for just about anything , and the for loop is one of its fundamental tools. You should understand it well and master it to build applications in Python.

A for loop allows you to iterate over a sequence that can be either a list, a tuple, a set, a dictionary, or a string . You use it if you need to execute the same code for each item of a sequence.

To explain the syntax of the for loop, we’ll start with a very basic example. Let’s say we want to keep track of the home countries of our students. So, we have the list new_students_countries , which contains the countries of origin for our three new students.

We use the for loop to access each country in the list and print it:

Here, for each country in the list new_students_countries , we execute the print() command. As a result, we get the name of each country printed out in the output.

Let’s go over the syntax of the for loop:

  • It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case).
  • Then, the in keyword is followed by the name of the sequence that we want to iterate.
  • The initializer section ends with “ : ”.
  • The body of the loop is indented and includes the code that we want to execute for each item of the sequence.

Practice writing for loops with the course Python Basics. Part 1 . It has 95 interactive exercises that cover basic Python topics, including loops.

Now that we’re familiar with the syntax, let’s move on to an example where the usefulness of the for loop is more apparent.

We continue with our example. We have the list new_students_countries with the home countries of the new students. We now also have the list students_countries with the home countries of the existing students. We will use the for loop to check each country in new_students_countries to see if we already have students from the same country:

As you can see, we start by initializing the variable new_countries with 0 value. Then, we iterate over the list new_students_countries , and check for each country in this list if it is in the list students_countries . If it is not, it is a new country for us, and we increase new_countries by 1.

Since there are three items in new_students_countries , the for loop runs three times. We find that we already have students from Germany, while Great Britain and Italy are new countries for our student community.

For Loops to Iterate Over Different Sequence Types

For loops and sets.

As mentioned before, for loops also work with sets . Actually, sets can be an even better fit for our previous example; if we have several new students from the same new country, we don’t want them to be counted multiple times as if we have more new countries than we actually have.

So, let’s consider the set new_students_countries with the countries for four new students, two of whom come from Italy. Except for replacing a list with a set, we can use the same code as the above:

Because we use a set instead of a list, we have correctly counted that only two new countries are added to our student community, even though we have three students coming from new countries.

For Loops and Tuples

We may also iterate over a tuple with the for loop. For example, if we have a tuple with the names of the new students, we can use the following code to ask the home country of each student:

For Loops and Dictionaries

There are many different ways to iterate over a dictionary; it is a topic for a separate discussion by itself. In this example, I iterate through the dictionary items, each of which are basically tuples. So, I specify in the loop header to unpack these tuples into key and value. This gives me access to both dictionary keys and dictionary values in the body of the loop.

If you want to refresh your knowledge about dictionaries and other data structures, consider joining our course Python Data Structures in Practice .

For Loops and Strings

While iterating over sequences like lists, sets, tuples, and dictionaries sounds like a trivial assignment, it is often very exciting for Python beginners to learn that strings are also sequences , and hence, can also be iterated over by using a for loop.

Let’s see an example of when you may need to iterate over a string.

We need each new student to create a password for his or her student account. Let’s say we have a requirement that at least one character in the password must be uppercase. We may use the for loop to iterate over all of the characters in a password to check if the requirement is met:

Here, we initialize the variable uppercase as False . Then, we iterate over every character ( char ) of the string password to check if it is uppercase. If the condition is met, we change the uppercase variable to True .

For Loops to Iterate Over a Range

If you are familiar with other programming languages, you’ve probably noticed that the for loop in Python is different. In other languages, you typically iterate within a range of numbers (from 1 to n, from 0 to n, from n to m), not over a sequence. That said, you can also do this in Python by using the range() function.

For Loops With range()

First, you can use the range() function to repeat something a certain number of times. For example, let’s say you want to create a new password ( password_new ) consisting of 8 random characters. You can use the following for loop to generate 8 random characters and merge them into one string called password_new :

In addition to the required stop argument (here, 8), the range() function also accepts optional start and step arguments. With these arguments, you can define the starting and the ending numbers of the sequence as well as the difference between each number in the sequence. For example, to get all even numbers from 4 to 10, inclusive, you can use the following for loop:

Note that we use 11, not 10, as the upper bound. The range() function does not include the upper bound in the output .

You may also use the range() function to access the iteration number within the body of the for loop. For example, let’s say we have a list of the student names ordered by their exam results, from the highest to the lowest. In the body of our for loop, we want to access not only the list values but also their index. We can use the range() function to iterate over the list n times, where n is the length of the list. Here, we calculate n by len(exam_rank) :

Note that we use i+1 to print meaningful results, since the index in Python starts at 0.

For Loops With enumerate()

A “Pythonic” way to track the index value in the for loop requires using the enumerate() function. It allows you to iterate over lists and tuples while also accessing the index of each element in the body of the for loop:

When combining the for loop with enumerate() , we have access to the current count ( place in our example) and the respective value ( student in our example) in the body of the loop. Optionally, we can specify the starting count argument to have it start from 1 as we have done, or from any other number that makes sense in your case.

Time to Practice For Loops in Python!

This is a general overview of the Python for loop just to quickly show you how it works and when you can use it. However, there is much more to learn, and even more importantly, you need lots of practice to master the Python for loop.

A good way to start practicing is with the Python courses that can be either free or paid. The course Python Basics. Part 1 is one of the best options for Python newbies. It covers all basic topics, including the for loop, the while loop, conditional statements, and many more. With 95 interactive exercises, this course gives you a strong foundation for becoming a powerful Python user. Here is a review of the Python Basics Course for those interested in learning more details.

If you’re determined to become a Python programmer, I recommend starting with the track Learn Programming with Python . It includes 5 courses with hundreds of interactive exercises, covering not only basics but also built-in algorithms and functions. They can help you write optimized applications and real Python games.

Thanks for reading and happy learning!

You may also like

variable assignment in for loop python

How Do You Write a SELECT Statement in SQL?

variable assignment in for loop python

What Is a Foreign Key in SQL?

variable assignment in for loop python

Enumerate and Explain All the Basic Elements of an SQL Query

The Walrus Operator: Python 3.8 Assignment Expressions

The Walrus Operator: Python 3.8 Assignment Expressions

Table of Contents

Hello, Walrus!

Implementation, lists and dictionaries, list comprehensions, while loops, witnesses and counterexamples, walrus operator syntax, walrus operator pitfalls.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Assignment Expressions and Using the Walrus Operator

Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions . Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator .

This tutorial is an in-depth introduction to the walrus operator. You will learn some of the motivations for the syntax update and explore some examples where assignment expressions can be useful.

In this tutorial, you’ll learn how to:

  • Identify the walrus operator and understand its meaning
  • Understand use cases for the walrus operator
  • Avoid repetitive code by using the walrus operator
  • Convert between code using the walrus operator and code using other assignment methods
  • Understand the impacts on backward compatibility when using the walrus operator
  • Use appropriate style in your assignment expressions

Note that all walrus operator examples in this tutorial require Python 3.8 or later to work.

Free Download: Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

Walrus Operator Fundamentals

Let’s start with some different terms that programmers use to refer to this new syntax. You’ve already seen a few in this tutorial.

The := operator is officially known as the assignment expression operator . During early discussions, it was dubbed the walrus operator because the := syntax resembles the eyes and tusks of a sideways walrus . You may also see the := operator referred to as the colon equals operator . Yet another term used for assignment expressions is named expressions .

To get a first impression of what assignment expressions are all about, start your REPL and play around with the following code:

Line 1 shows a traditional assignment statement where the value False is assigned to walrus . Next, on line 5, you use an assignment expression to assign the value True to walrus . After both lines 1 and 5, you can refer to the assigned values by using the variable name walrus .

You might be wondering why you’re using parentheses on line 5, and you’ll learn why the parentheses are needed later on in this tutorial .

Note: A statement in Python is a unit of code. An expression is a special statement that can be evaluated to some value.

For example, 1 + 2 is an expression that evaluates to the value 3 , while number = 1 + 2 is an assignment statement that doesn’t evaluate to a value. Although running the statement number = 1 + 2 doesn’t evaluate to 3 , it does assign the value 3 to number .

In Python, you often see simple statements like return statements and import statements , as well as compound statements like if statements and function definitions . These are all statements, not expressions.

There’s a subtle—but important—difference between the two types of assignments seen earlier with the walrus variable. An assignment expression returns the value, while a traditional assignment doesn’t. You can see this in action when the REPL doesn’t print any value after walrus = False on line 1, while it prints out True after the assignment expression on line 5.

You can see another important aspect about walrus operators in this example. Though it might look new, the := operator does not do anything that isn’t possible without it. It only makes certain constructs more convenient and can sometimes communicate the intent of your code more clearly.

Note: You need at least Python 3.8 to try out the examples in this tutorial. If you don’t already have Python 3.8 installed and you have Docker available, a quick way to start working with Python 3.8 is to run one of the official Docker images :

This will download and run the latest stable version of Python 3.8. For more information, see Run Python Versions in Docker: How to Try the Latest Python Release .

Now you have a basic idea of what the := operator is and what it can do. It’s an operator used in assignment expressions, which can return the value being assigned, unlike traditional assignment statements. To get deeper and really learn about the walrus operator, continue reading to see where you should and shouldn’t use it.

Like most new features in Python, assignment expressions were introduced through a Python Enhancement Proposal (PEP). PEP 572 describes the motivation for introducing the walrus operator, the details of the syntax, as well as examples where the := operator can be used to improve your code.

This PEP was originally written by Chris Angelico in February 2018. Following some heated discussion, PEP 572 was accepted by Guido van Rossum in July 2018. Since then, Guido announced that he was stepping down from his role as benevolent dictator for life (BDFL) . Starting in early 2019, Python has been governed by an elected steering council instead.

The walrus operator was implemented by Emily Morehouse , and made available in the first alpha release of Python 3.8.

In many languages, including C and its derivatives, assignment statements function as expressions. This can be both very powerful and also a source of confusing bugs. For example, the following code is valid C but doesn’t execute as intended:

Here, if (x = y) will evaluate to true and the code snippet will print out x and y are equal (x = 8, y = 8) . Is this the result you were expecting? You were trying to compare x and y . How did the value of x change from 3 to 8 ?

The problem is that you’re using the assignment operator ( = ) instead of the equality comparison operator ( == ). In C, x = y is an expression that evaluates to the value of y . In this example, x = y is evaluated as 8 , which is considered truthy in the context of the if statement.

Take a look at a corresponding example in Python. This code raises a SyntaxError :

Unlike the C example, this Python code gives you an explicit error instead of a bug.

The distinction between assignment statements and assignment expressions in Python is useful in order to avoid these kinds of hard-to-find bugs. PEP 572 argues that Python is better suited to having different syntax for assignment statements and expressions instead of turning the existing assignment statements into expressions.

One design principle underpinning the walrus operator is that there are no identical code contexts where both an assignment statement using the = operator and an assignment expression using the := operator would be valid. For example, you can’t do a plain assignment with the walrus operator:

In many cases, you can add parentheses ( () ) around the assignment expression to make it valid Python:

Writing a traditional assignment statement with = is not allowed inside such parentheses. This helps you catch potential bugs.

Later on in this tutorial , you’ll learn more about situations where the walrus operator is not allowed, but first you’ll learn about the situations where you might want to use them.

Walrus Operator Use Cases

In this section, you’ll see several examples where the walrus operator can simplify your code. A general theme in all these examples is that you’ll avoid different kinds of repetition:

  • Repeated function calls can make your code slower than necessary.
  • Repeated statements can make your code hard to maintain.
  • Repeated calls that exhaust iterators can make your code overly complex.

You’ll see how the walrus operator can help in each of these situations.

Arguably one of the best use cases for the walrus operator is when debugging complex expressions. Say that you want to find the distance between two locations along the earth’s surface. One way to do this is to use the haversine formula :

The haversine formula

ϕ represents the latitude and λ represents the longitude of each location. To demonstrate this formula, you can calculate the distance between Oslo (59.9°N 10.8°E) and Vancouver (49.3°N 123.1°W) as follows:

As you can see, the distance from Oslo to Vancouver is just under 7200 kilometers.

Note: Python source code is typically written using UTF-8 Unicode . This allows you to use Greek letters like ϕ and λ in your code, which may be useful when translating mathematical formulas. Wikipedia shows some alternatives for using Unicode on your system.

While UTF-8 is supported (in string literals, for instance), Python’s variable names use a more limited character set . For example, you can’t use emojis while naming your variables. That is a good restriction !

Now, say that you need to double-check your implementation and want to see how much the haversine terms contribute to the final result. You could copy and paste the term from your main code to evaluate it separately. However, you could also use the := operator to give a name to the subexpression you’re interested in:

The advantage of using the walrus operator here is that you calculate the value of the full expression and keep track of the value of ϕ_hav at the same time. This allows you to confirm that you did not introduce any errors while debugging.

Lists are powerful data structures in Python that often represent a series of related attributes. Similarly, dictionaries are used all over Python and are great for structuring information.

Sometimes when setting up these data structures, you end up performing the same operation several times. As a first example, calculate some basic descriptive statistics of a list of numbers and store them in a dictionary:

Note that both the sum and the length of the numbers list are calculated twice. The consequences are not too bad in this simple example, but if the list was larger or the calculations were more complicated, you might want to optimize the code. To do this, you can first move the function calls out of the dictionary definition:

The variables num_length and num_sum are only used to optimize the calculations inside the dictionary. By using the walrus operator, this role can be made more clear:

num_length and num_sum are now defined inside the definition of description . This is a clear hint to anybody reading this code that these variables are just used to optimize these calculations and aren’t used again later.

Note: The scope of the num_length and num_sum variables is the same in the example with the walrus operator and in the example without. This means that in both examples, the variables are available after the definition of description .

Even though both examples are very similar functionally, a benefit of using the assignment expressions is that the := operator communicates the intent of these variables as throwaway optimizations.

In the next example, you’ll work with a bare-bones implementation of the wc utility for counting lines, words, and characters in a text file:

This script can read one or several text files and report how many lines, words, and characters each of them contains. Here’s a breakdown of what’s happening in the code:

  • Line 6 loops over each filename provided by the user. sys.argv is a list containing each argument given on the command line, starting with the name of your script. For more information about sys.argv , you can check out Python Command Line Arguments .
  • Line 7 translates each filename string to a pathlib.Path object . Storing a filename in a Path object allows you to conveniently read the text file in the next lines.
  • Lines 8 to 12 construct a tuple of counts to represent the number of lines, words, and characters in one text file.
  • Line 9 reads a text file and calculates the number of lines by counting newlines.
  • Line 10 reads a text file and calculates the number of words by splitting on whitespace.
  • Line 11 reads a text file and calculates the number of characters by finding the length of the string.
  • Line 13 prints all three counts together with the filename to the console. The *counts syntax unpacks the counts tuple. In this case, the print() statement is equivalent to print(counts[0], counts[1], counts[2], path) .

To see wc.py in action, you can use the script on itself as follows:

In other words, the wc.py file consists of 13 lines, 34 words, and 316 characters.

If you look closely at this implementation, you’ll notice that it’s far from optimal. In particular, the call to path.read_text() is repeated three times. That means that each text file is read three times. You can use the walrus operator to avoid the repetition:

The contents of the file are assigned to text , which is reused in the next two calculations. The program still functions the same:

As in the earlier examples, an alternative approach is to define text before the definition of counts :

While this is one line longer than the previous implementation, it probably provides the best balance between readability and efficiency. The := assignment expression operator isn’t always the most readable solution even when it makes your code more concise.

List comprehensions are great for constructing and filtering lists. They clearly state the intent of the code and will usually run quite fast.

There’s one list comprehension use case where the walrus operator can be particularly useful. Say that you want to apply some computationally expensive function, slow() , to the elements in your list and filter on the resulting values. You could do something like the following:

Here, you filter the numbers list and leave the positive results from applying slow() . The problem with this code is that this expensive function is called twice.

A very common solution for this type of situation is rewriting your code to use an explicit for loop:

This will only call slow() once. Unfortunately, the code is now more verbose, and the intent of the code is harder to understand. The list comprehension had clearly signaled that you were creating a new list, while this is more hidden in the explicit for loop since several lines of code separate the list creation and the use of .append() . Additionally, the list comprehension runs faster than the repeated calls to .append() .

You can code some other solutions by using a filter() expression or a kind of double list comprehension:

The good news is that there’s only one call to slow() for each number. The bad news is that the code’s readability has suffered in both expressions.

Figuring out what’s actually happening in the double list comprehension takes a fair amount of head-scratching. Essentially, the second for statement is used only to give the name value to the return value of slow(num) . Fortunately, that sounds like something that can instead be performed with an assignment expression!

You can rewrite the list comprehension using the walrus operator as follows:

Note that the parentheses around value := slow(num) are required. This version is effective, readable, and communicates the intent of the code well.

Note: You need to add the assignment expression on the if clause of the list comprehension. If you try to define value with the other call to slow() , then it will not work:

This will raise a NameError because the if clause is evaluated before the expression at the beginning of the comprehension.

Let’s look at a slightly more involved and practical example. Say that you want to use the Real Python feed to find the titles of the last episodes of the Real Python Podcast .

You can use the Real Python Feed Reader to download information about the latest Real Python publications. In order to find the podcast episode titles, you’ll use the third-party Parse package. Start by installing both into your virtual environment :

You can now read the latest titles published by Real Python :

Podcast titles start with "The Real Python Podcast" , so here you can create a pattern that Parse can use to identify them:

Compiling the pattern beforehand speeds up later comparisons, especially when you want to match the same pattern over and over. You can check if a string matches your pattern using either pattern.parse() or pattern.search() :

Note that Parse is able to pick out the podcast episode number and the episode name. The episode number is converted to an integer data type because you used the :d format specifier .

Let’s get back to the task at hand. In order to list all the recent podcast titles, you need to check whether each string matches your pattern and then parse out the episode title. A first attempt may look something like this:

Though it works, you might notice the same problem you saw earlier. You’re parsing each title twice because you filter out titles that match your pattern and then use that same pattern to pick out the episode title.

Like you did earlier, you can avoid the double work by rewriting the list comprehension using either an explicit for loop or a double list comprehension. Using the walrus operator, however, is even more straightforward:

Assignment expressions work well to simplify these kinds of list comprehensions. They help you keep your code readable while you avoid doing a potentially expensive operation twice.

Note: The Real Python Podcast has its own separate RSS feed , which you should use if you want to play around with information only about the podcast. You can get all the episode titles with the following code:

See The Real Python Podcast for options to listen to it using your podcast player.

In this section, you’ve focused on examples where list comprehensions can be rewritten using the walrus operator. The same principles also apply if you see that you need to repeat an operation in a dictionary comprehension , a set comprehension , or a generator expression .

The following example uses a generator expression to calculate the average length of episode titles that are over 50 characters long:

The generator expression uses an assignment expression to avoid calculating the length of each episode title twice.

Python has two different loop constructs: for loops and while loops . You typically use a for loop when you need to iterate over a known sequence of elements. A while loop, on the other hand, is used when you don’t know beforehand how many times you’ll need to loop.

In while loops, you need to define and check the ending condition at the top of the loop. This sometimes leads to some awkward code when you need to do some setup before performing the check. Here’s a snippet from a multiple-choice quiz program that asks the user to answer a question with one of several valid answers:

This works but has an unfortunate repetition of identical input() lines. It’s necessary to get at least one answer from the user before checking whether it’s valid or not. You then have a second call to input() inside the while loop to ask for a second answer in case the original user_answer wasn’t valid.

If you want to make your code more maintainable, it’s quite common to rewrite this kind of logic with a while True loop. Instead of making the check part of the main while statement, the check is performed later in the loop together with an explicit break :

This has the advantage of avoiding the repetition. However, the actual check is now harder to spot.

Assignment expressions can often be used to simplify these kinds of loops. In this example, you can now put the check back together with while where it makes more sense:

The while statement is a bit denser, but the code now communicates the intent more clearly without repeated lines or seemingly infinite loops.

You can expand the box below to see the full code of the multiple-choice quiz program and try a couple of questions about the walrus operator yourself.

Full source code of multiple-choice quiz program Show/Hide

This script runs a multiple-choice quiz. You’ll be asked each of the questions in order, but the order of answers will be shuffled each time:

Note that the first answer is assumed to be the correct one. You can add more questions to the quiz yourself. Feel free to share your questions with the community in the comments section below the tutorial!

You can often simplify while loops by using assignment expressions. The original PEP shows an example from the standard library that makes the same point.

In the examples you’ve seen so far, the := assignment expression operator does essentially the same job as the = assignment operator in your old code. You’ve seen how to simplify code, and now you’ll learn about a different type of use case that’s made possible by this new operator.

In this section, you’ll learn how you can find witnesses when calling any() by using a clever trick that isn’t possible without using the walrus operator. A witness, in this context, is an element that satisfies the check and causes any() to return True .

By applying similar logic, you’ll also learn how you can find counterexamples when working with all() . A counterexample, in this context, is an element that doesn’t satisfy the check and causes all() to return False .

In order to have some data to work with, define the following list of city names:

You can use any() and all() to answer questions about your data:

In each of these cases, any() and all() give you plain True or False answers. What if you’re also interested in seeing an example or a counterexample of the city names? It could be nice to see what’s causing your True or False result:

Does any city name start with "H" ?

Yes, because "Houston" starts with "H" .

Do all city names start with "H" ?

No, because "Oslo" doesn’t start with "H" .

In other words, you want a witness or a counterexample to justify the answer.

Capturing a witness to an any() expression has not been intuitive in earlier versions of Python. If you were calling any() on a list and then realized you also wanted a witness, you’d typically need to rewrite your code:

Here, you first capture all city names that start with "H" . Then, if there’s at least one such city name, you print out the first city name starting with "H" . Note that here you’re actually not using any() even though you’re doing a similar operation with the list comprehension.

By using the := operator, you can find witnesses directly in your any() expressions:

You can capture a witness inside the any() expression. The reason this works is a bit subtle and relies on any() and all() using short-circuit evaluation : they only check as many items as necessary to determine the result.

Note: If you want to check whether all city names start with the letter "H" , then you can look for a counterexample by replacing any() with all() and updating the print() functions to report the first item that doesn’t pass the check.

You can see what’s happening more clearly by wrapping .startswith("H") in a function that also prints out which item is being checked:

Note that any() doesn’t actually check all items in cities . It only checks items until it finds one that satisfies the condition. Combining the := operator and any() works by iteratively assigning each item that is being checked to witness . However, only the last such item survives and shows which item was last checked by any() .

Even when any() returns False , a witness is found:

However, in this case, witness doesn’t give any insight. 'Holguín' doesn’t contain ten or more characters. The witness only shows which item happened to be evaluated last.

One of the main reasons assignments were not expressions in Python from the beginning is that the visual likeness of the assignment operator ( = ) and the equality comparison operator ( == ) could potentially lead to bugs. When introducing assignment expressions, a lot of thought was put into how to avoid similar bugs with the walrus operator. As mentioned earlier , one important feature is that the := operator is never allowed as a direct replacement for the = operator, and vice versa.

As you saw at the beginning of this tutorial, you can’t use a plain assignment expression to assign a value:

It’s syntactically legal to use an assignment expression to only assign a value, but only if you add parentheses:

Even though it’s possible, however, this really is a prime example of where you should stay away from the walrus operator and use a traditional assignment statement instead.

PEP 572 shows several other examples where the := operator is either illegal or discouraged. The following examples all raise a SyntaxError :

In all these cases, you’re better served using = instead. The next examples are similar and are all legal code. However, the walrus operator doesn’t improve your code in any of these cases:

None of these examples make your code more readable. You should instead do the extra assignment separately by using a traditional assignment statement. See PEP 572 for more details about the reasoning.

There’s one use case where the := character sequence is already valid Python. In f-strings , a colon ( : ) is used to separate values from their format specification . For example:

The := in this case does look like a walrus operator, but the effect is quite different. To interpret x:=8 inside the f-string, the expression is broken into three parts: x , : , and =8 .

Here, x is the value, : acts as a separator, and =8 is a format specification. According to Python’s Format Specification Mini-Language , in this context = specifies an alignment option. In this case, the value is padded with spaces in a field of width 8 .

To use assignment expressions inside f-strings, you need to add parentheses:

This updates the value of x as expected. However, you’re probably better off using traditional assignments outside of your f-strings instead.

Let’s look at some other situations where assignment expressions are illegal:

Attribute and item assignment: You can only assign to simple names, not dotted or indexed names:

This fails with a descriptive error message. There’s no straightforward workaround.

Iterable unpacking: You can’t unpack when using the walrus operator:

If you add parentheses around the whole expression, it will be interpreted as a 3-tuple with the three elements lat , 59.9 , and 10.8 .

Augmented assignment: You can’t use the walrus operator combined with augmented assignment operators like += . This raises a SyntaxError :

The easiest workaround would be to do the augmentation explicitly. You could, for example, do (count := count + 1) . PEP 577 originally described how to add augmented assignment expressions to Python, but the proposal was withdrawn.

When you’re using the walrus operator, it will behave similarly to traditional assignment statements in many respects:

The scope of the assignment target is the same as for assignments. It will follow the LEGB rule . Typically, the assignment will happen in the local scope, but if the target name is already declared global or nonlocal , that is honored.

The precedence of the walrus operator can cause some confusion. It binds less tightly than all other operators except the comma, so you might need parentheses to delimit the expression that is assigned. As an example, note what happens when you don’t use parentheses:

square is bound to the whole expression number ** 2 > 5 . In other words, square gets the value True and not the value of number ** 2 , which was the intention. In this case, you can delimit the expression with parentheses:

The parentheses make the if statement both clearer and actually correct.

There’s one final gotcha. When assigning a tuple using the walrus operator, you always need to use parentheses around the tuple. Compare the following assignments:

Note that in the second example, walrus takes the value 3.8 and not the whole tuple 3.8, True . That’s because the := operator binds more tightly than the comma. This may seem a bit annoying. However, if the := operator bound less tightly than the comma, it would not be possible to use the walrus operator in function calls with more than one argument.

The style recommendations for the walrus operator are mostly the same as for the = operator used for assignment. First, always add spaces around the := operator in your code. Second, use parentheses around the expression as necessary, but avoid adding extra parentheses that are not needed.

The general design of assignment expressions is to make them easy to use when they are helpful but to avoid overusing them when they might clutter up your code.

The walrus operator is a new syntax that is only available in Python 3.8 and later. This means that any code you write that uses the := syntax will only work on the most recent versions of Python.

If you need to support older versions of Python, you can’t ship code that uses assignment expressions. There are some projects, like walrus , that can automatically translate walrus operators into code that is compatible with older versions of Python. This allows you to take advantage of assignment expressions when writing your code and still distribute code that is compatible with more Python versions.

Experience with the walrus operator indicates that := will not revolutionize Python. Instead, using assignment expressions where they are useful can help you make several small improvements to your code that could benefit your work overall.

There are many times it’s possible for you to use the walrus operator, but where it won’t necessarily improve the readability or efficiency of your code. In those cases, you’re better off writing your code in a more traditional manner.

You now know how the new walrus operator works and how you can use it in your own code. By using the := syntax, you can avoid different kinds of repetition in your code and make your code both more efficient and easier to read and maintain. At the same time, you shouldn’t use assignment expressions everywhere. They will only help you in some use cases.

In this tutorial, you learned how to:

To learn more about the details of assignment expressions, see PEP 572 . You can also check out the PyCon 2019 talk PEP 572: The Walrus Operator , where Dustin Ingram gives an overview of both the walrus operator and the discussion around the new PEP.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Geir Arne Hjelle

Geir Arne Hjelle

Geir Arne is an avid Pythonista and a member of the Real Python tutorial team.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal . Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session . Happy Pythoning!

Keep Learning

Related Topics: intermediate best-practices

Recommended Video Course: Python Assignment Expressions and Using the Walrus Operator

Keep reading Real Python by creating a free account or signing in:

Already have an account? Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Tricks: The Book

"Python Tricks: The Book" – Free Sample Chapter (PDF)

🔒 No spam. We take your privacy seriously.

variable assignment in for loop python

  • Python »
  • 3.12.4 Documentation »
  • The Python Tutorial »
  • 3. An Informal Introduction to Python
  • Theme Auto Light Dark |

3. An Informal Introduction to Python ¶

In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

Some examples:

3.1. Using Python as a Calculator ¶

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>> . (It shouldn’t take long.)

3.1.1. Numbers ¶

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators + , - , * and / can be used to perform arithmetic; parentheses ( () ) can be used for grouping. For example:

The integer numbers (e.g. 2 , 4 , 20 ) have type int , the ones with a fractional part (e.g. 5.0 , 1.6 ) have type float . We will see more about numeric types later in the tutorial.

Division ( / ) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use % :

With Python, it is possible to use the ** operator to calculate powers [ 1 ] :

The equal sign ( = ) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

In interactive mode, the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

In addition to int and float , Python supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j ).

3.1.2. Text ¶

Python can manipulate text (represented by type str , so-called “strings”) as well as numbers. This includes characters “ ! ”, words “ rabbit ”, names “ Paris ”, sentences “ Got your back. ”, etc. “ Yay! :) ”. They can be enclosed in single quotes ( '...' ) or double quotes ( "..." ) with the same result [ 2 ] .

To quote a quote, we need to “escape” it, by preceding it with \ . Alternatively, we can use the other type of quotation marks:

In the Python shell, the string definition and output string can look different. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds.

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...''' . End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

produces the following output (note that the initial newline is not included):

Strings can be concatenated (glued together) with the + operator, and repeated with * :

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

This feature is particularly useful when you want to break long strings:

This only works with two literals though, not with variables or expressions:

If you want to concatenate variables or a variable and a literal, use + :

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s :

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n , for example:

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j , respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used for slicing:

Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

Strings are examples of sequence types , and support the common operations supported by such types.

Strings support a large number of methods for basic transformations and searching.

String literals that have embedded expressions.

Information about string formatting with str.format() .

The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.

3.1.3. Lists ¶

Python knows a number of compound data types, used to group together other values. The most versatile is the list , which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

Lists also support operations like concatenation:

Unlike strings, which are immutable , lists are a mutable type, i.e. it is possible to change their content:

You can also add new items at the end of the list, by using the list.append() method (we will see more about methods later):

Simple assignment in Python never copies data. When you assign a list to a variable, the variable refers to the existing list . Any changes you make to the list through one variable will be seen through all other variables that refer to it.:

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists), for example:

3.2. First Steps Towards Programming ¶

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

This example introduces several new features.

The first line contains a multiple assignment : the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

The while loop executes as long as the condition (here: a < 10 ) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

The body of the loop is indented : indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

Table of Contents

  • 3.1.1. Numbers
  • 3.1.2. Text
  • 3.1.3. Lists
  • 3.2. First Steps Towards Programming

Previous topic

2. Using the Python Interpreter

4. More Control Flow Tools

  • Report a Bug
  • Show Source
  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assign variable in while loop condition in Python?

I just came across this piece of code

and thought, there must be a better way to do this, than using an infinite loop with break .

So I tried:

and, obviously, got an error.

Is there any way to avoid using a break in that situation?

Ideally, you'd want to avoid saying readline twice... IMHO, repeating is even worse than just a break , especially if the statement is complex.

  • variable-assignment

Community's user avatar

  • 3 While this is a good question and I think the for line in data solution is a good fit for this specific problem, I don't think there's anything wrong with the while True: ... break idiom. Don't be afraid of it. :-) –  Kirk Strauser Commented Jul 8, 2011 at 22:53
  • 4 These answers provide alternatives to assignment in the conditional of the while-loop, but really don't answer the question: is there a way to do assignment in the while-loop? I'm running into this same problem, trying to do while (character = string[i]): I know that a for-loop is a better way to iterate over a string, but my conditional is actually much more complex than this, and I want to do this assignment as the right-hand side of an "or" within the conditional. –  user2760926 Commented Sep 9, 2013 at 9:30
  • 1 @KirkStrauser The problem with the break construction is, that it is using four lines to express something, which other languages can do in just one line. However it does the right thing. None of the answers given so far has provided a better general purpose solution. They either only work with iterators or duplicate the assignment, which is worse than three extra lines of code for the break version. –  kasperd Commented Nov 21, 2014 at 3:18

10 Answers 10

Starting Python 3.8 , and the introduction of assignment expressions (PEP 572) ( := operator), it's now possible to capture the condition value ( data.readline() ) of the while loop as a variable ( line ) in order to re-use it within the body of the loop:

Xavier Guihot's user avatar

  • 4 As a side note, an explicit condition may be written as while (line := data.readline()) is not None: –  Hi-Angel Commented May 18, 2023 at 15:00

Try this one, works for files opened with open('filename')

Niklas Claesson's user avatar

  • 3 +1 for being exemplified in the python core documentation: docs.python.org/2/library/functions.html#iter –  ThorSummoner Commented Oct 15, 2014 at 2:59

If you aren't doing anything fancier with data, like reading more lines later on, there's always:

Ned Batchelder's user avatar

  • I was trying to play Stump The Sushi Eater by thinking of a type of object data might be that would support .readline() but not __iter__(). I'm drawing a blank. Do you know of any offhand? –  Kirk Strauser Commented Jul 8, 2011 at 22:32
  • Doesn't this require reading the entire file into memory first? That doesn't seem applicable for large files. (Especially if the file is larger than your ram can hold!) –  ThorSummoner Commented Oct 15, 2014 at 2:48
  • 1 If data is a file object (which is an odd name, but that's the way the OP used it), then the entire file will not be read into memory. for line in data will iterate over lines, reading them as needed. –  Ned Batchelder Commented Oct 15, 2014 at 11:37
  • 1 @NedBatchelder: according to the docs at docs.python.org/2/library/stdtypes.html#file.next - and my unfortunate experience - the filepointer is not where you'd expect it to be (e.g. for a data.tell() ) with for line in data and might even be at the end of the file even before the last line is read. So, it doesn't quite "read them as needed" if you're counting on python/os to do the accounting of where you are in the file. –  mpag Commented Jan 5, 2017 at 18:25
  • 2 @mpag There's definitely no guarantee (and I didn't mean to imply there was) that each line is read precisely as needed. I was countering the notion that the entire file would be read into memory. If you are iterating by lines, you can't make any assumptions about where the file pointer is. –  Ned Batchelder Commented Jan 5, 2017 at 22:23

This isn't much better, but this is the way I usually do it. Python doesn't return the value upon variable assignment like other languages (e.g., Java).

cwallenpoole's user avatar

  • 7 I'm not a big fan of that, especially if ... do stuff ... is sizable as it requires you to keep the flow of the entire loop in mind as you hack around on it. For example, if you add something like if line.startswith('foo'): continue later without realizing that line is only updated at the very end, then you've accidentally created an infinite loop. –  Kirk Strauser Commented Jul 8, 2011 at 22:22
  • 1 @Kirk - In part, I agree ,but the alternatives aren't much better. Ideally, the class you're using implements a generator and you can just use a for loop, but there are certain cases where you need a while loop ( e.g., 'while cur_time>expected_time:'). I don't know if the OPs post is much better, but I suppose its a matter of opinion :) –  dfb Commented Jul 8, 2011 at 22:33
  • A classic while loop, and understandable for any quality of programmer. Probably the best choice for future maintenance purposes. –  Kim Commented Jan 24, 2019 at 17:09
  • 2 @Kirk Strauser One could argue if ... do stuff ... is so long you lost track of what's going on in your loop then you're probably doing it wrong. –  arkan Commented Apr 26, 2019 at 6:11

? It large depends on the semantics of the data object's readline semantics. If data is a file object, that'll work.

Kirk Strauser's user avatar

Will iterate over each line in the file , rather than using a while . It is a much more common idiom for the task of reading a file in my experience (in Python).

In fact, data does not have to be a file but merely provide an iterator.

shelhamer's user avatar

According to the FAQ from Python's documentation, iterating over the input with for construct or running an infinite while True loop and using break statement to terminate it, are preferred and idiomatic ways of iteration.

Mr. Deathless's user avatar

If data is a file, as stated in other answers, using for line in file will work fine. If data is not a file, and a random data reading object, then you should implement it as an iterator, implementing __iter__ and next methods.

The next method should to the reading, check if there is more data, and if not, raise StopIteration . If you do this, you can continue using the for line in data idiom.

rafalotufo's user avatar

You could do:

brandon's user avatar

  • 8 That will execute the body of the loop one more time than it is supposed to. –  kasperd Commented Nov 21, 2014 at 3:15

If data has a function that returns an iterator instead of readline (say data.iterate ), you could simply do:

TorelTwiddler's user avatar

  • 1 Don't do that unless you know data is tiny (and really not even then) as .readlines() slurps the entire contents into RAM, but it doesn't really buy you anything in return. –  Kirk Strauser Commented Jul 8, 2011 at 22:30
  • It should work fine if the function returns an iterator instead of the entire list, correct? –  TorelTwiddler Commented Jul 8, 2011 at 22:38
  • Yes, but I haven't seen .readlines() implemented that way. The docs for file.readlines() say that it will "[r]ead until EOF using readline() and return a list containing the lines thus read." –  Kirk Strauser Commented Jul 8, 2011 at 22:49
  • I like that answer better. :-) However, the usual name for iterate is __iter__ , and then you can re-write the loop as for line in data . –  Kirk Strauser Commented Jul 8, 2011 at 22:55
  • True, but I'm going to leave it like this, since there are already 4 other answers that have for line in data . =D –  TorelTwiddler Commented Jul 8, 2011 at 23:02

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python while-loop variable-assignment or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • What aspects define how present the garlic taste in an aglio e olio pasta becomes?
  • Do rich parents pay less in child support if they didn't provide a rich lifestyle for their family pre-divorce?
  • How many steps in mille passuum?
  • Bibliographic references: “[19,31-33]”, “[33,19,31,32]” or “[33], [19], [31], [32]”?
  • How much time is needed to judge an Earth-like planet to be safe?
  • Will a nitro aryl resist an halogen exchange using nBuLi?
  • Why is "Colourless green ideas sleep furiously" considered meaningless?
  • Could alien species with blood based on different elements eat the same food?
  • Recommendations Modifying/increasing a bicycles Max Weight limits
  • How do I perform pandas cumsum while skipping rows that are duplicated in another field?
  • Starship IFT-4: whatever happened to the fin tip camera feed?
  • Read metaplex metadata in rust & anchor
  • How should I end a campaign only the passive players are enjoying?
  • Approximating the probability that two Binomial variables are equal
  • Error relinking cloned line items to the cloned sobject record
  • Potential difference when two emf sources are connected in a simple loop circuit
  • How to count the number of lines in an array
  • How can I have two plots progress on different rates of time?
  • Should I practise a piece at a metronome tempo that is faster than required?
  • Create sublists whose totals exceed a certain threshold and that are as short as possible
  • Who is the "Sir Oracle" being referenced in "Dracula"?
  • Is a possessive apostrophe appropriate in the verb phrase 'to save someone something'?
  • UTF-8 characters in POSIX shell script *comments* - anything against it?
  • What was Jessica and the Bene Gesserit's game plan if Paul failed the test?

variable assignment in for loop python

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

  • Python if...else Statement
  • Python for Loop

Python while Loop

Python break and continue

Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Sets
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Assert Statement

  • List of Keywords in Python

In computer programming, the if statement is a conditional statement. It is used to execute a block of code only when a specific condition is met. For example,

Suppose we need to assign different grades to students based on their scores.

  • If a student scores above 90 , assign grade A
  • If a student scores above 75 , assign grade B
  • If a student scores above 65 , assign grade C

These conditional tasks can be achieved using the if statement.

  • Python if Statement

An if statement executes a block of code only if the specified condition is met.

Here, if the condition of the if statement is:

  • True - the body of the if statement executes.
  • False - the body of the if statement is skipped from execution.

Let's look at an example.

Working of if Statement

Note: Be mindful of the indentation while writing the if statements. Indentation is the whitespace at the beginning of the code.

Here, the spaces before the print() statement denote that it's the body of the if statement.

  • Example: Python if Statement

Sample Output 1

In the above example, we have created a variable named number . Notice the test condition ,

As the number is greater than 0 , the condition evaluates True . Hence, the body of the if statement executes.

Sample Output 2

Now, let's change the value of the number to a negative integer, say -5 .

Now, when we run the program, the output will be:

This is because the value of the number is less than 0 . Hence, the condition evaluates to False . And, the body of the if statement is skipped.

An if statement can have an optional else clause. The else statement executes if the condition in the if statement evaluates to False .

Here, if the condition inside the if statement evaluates to

  • True - the body of if executes, and the body of else is skipped.
  • False - the body of else executes, and the body of if is skipped

Working of if…else Statement

  • Example: Python if…else Statement

In the above example, we have created a variable named number .

Since the value of the number is 10 , the condition evaluates to True . Hence, code inside the body of if is executed.

If we change the value of the variable to a negative integer, let's say -5 , our output will be:

Here, the test condition evaluates to False . Hence code inside the body of else is executed.

  • Python if…elif…else Statement

The if...else statement is used to execute a block of code among two alternatives.

However, if we need to make a choice between more than two alternatives, we use the if...elif...else statement.

  • if condition1 - This checks if condition1 is True . If it is, the program executes code block 1 .
  • elif condition2 - If condition1 is not True , the program checks condition2 . If condition2 is True , it executes code block 2 .
  • else - If neither condition1 nor condition2 is True , the program defaults to executing code block 3 .

Working of if…elif…else Statement

  • Example: Python if…elif…else Statement

Since the value of the number is 0 , both the test conditions evaluate to False .

Hence, the statement inside the body of else is executed.

  • Python Nested if Statements

It is possible to include an if statement inside another if statement. For example,

Here's how this program works.

Working of Nested if Statement

More on Python if…else Statement

In certain situations, the if statement can be simplified into a single line. For example,

This code can be compactly written as

This one-liner approach retains the same functionality but in a more concise format.

Python doesn't have a ternary operator. However, we can use if...else to work like a ternary operator in other languages. For example,

can be written as

We can use logical operators such as and and or within an if statement.

Here, we used the logical operator and to add two conditions in the if statement.

We also used >= (comparison operator) to compare two values.

Logical and comparison operators are often used with if...else statements. Visit Python Operators to learn more.

Table of Contents

  • Introduction

Write a function to check whether a student passed or failed his/her examination.

  • Assume the pass marks to be 50 .
  • Return Passed if the student scored more than 50. Otherwise, return Failed .

Video: Python if...else Statement

Sorry about that.

Related Tutorials

Python Tutorial

IMAGES

  1. Python For Loops Explained (Python for Data Science Basics #5)

    variable assignment in for loop python

  2. For Loop 2 Variables Python

    variable assignment in for loop python

  3. For Loop in Python Explained with Examples

    variable assignment in for loop python

  4. Variable Assignment in Python

    variable assignment in for loop python

  5. Python For Loops Explained (Python for Data Science Basics #5)

    variable assignment in for loop python

  6. For Loop In Python Explained With Examples Simplilear

    variable assignment in for loop python

VIDEO

  1. Assignment-14||Loop control statements in python||ccbp||Nxtwave... assignments

  2. Loop Control Statements

  3. How to use for loop in python

  4. "Mastering Assignment Operators in Python: A Comprehensive Guide"

  5. Python Simple Variable Assignment

  6. #6 Python Variable Assignment Part_1 (Variables in Python)

COMMENTS

  1. Python Variable assignment in a for loop

    print(x) (Note I expanded x += 3 to x = x + 3 to increase visibility for the name accesses - read and write.) First, you bind the list [1, 2, 3] to the name a. Then, you iterate over the list. During each iteration, the value is bound to the name x in the current scope. Your assignment then assigns another value to x.

  2. Python "for" Loops (Definite Iteration)

    The loop body is executed once for each item next() returns, with loop variable i set to the given item for each iteration. This sequence of events is summarized in the following diagram: Schematic Diagram of a Python for Loop. Perhaps this seems like a lot of unnecessary monkey business, but the benefit is substantial.

  3. For-Loops

    The variable n is assigned the value n + i (\(1 + 2 = 3\)). The variable i is assigned the value 3. The variable n is assigned the value n + i (\(3 + 3 = 6\)). With no more values to assign in the list, the for-loop is terminated with n = 6. We present several more examples to give you a sense of how for-loops work.

  4. Python For Loops

    Python For Loops. 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.. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

  5. Python for Loop (With Examples)

    for Loop with Python range () In Python, the range () function returns a sequence of numbers. For example, Here, range(4) returns a sequence of 0, 1, 2 ,and 3. Since the range() function returns a sequence of numbers, we can iterate over it using a for loop. For example, print(i) Output.

  6. Python's Assignment Operator: Write Robust Assignments

    Here, variable represents a generic Python variable, while expression represents any Python object that you can provide as a concrete value—also known as a literal—or an expression that evaluates to a value. To execute an assignment statement like the above, Python runs the following steps: Evaluate the right-hand expression to produce a concrete value or object.

  7. For Loops in Python

    A for loop in Python has a shorter, and a more readable and intuitive syntax. The general syntax for a for loop in Python looks like this: for placeholder_variable in sequence: # code that does something Let's break it down: To start the for loop, you first have to use the for keyword. The placeholder_variable is an arbitrary variable. It ...

  8. Using multiple variables in a For loop in Python

    On each iteration of the for loop, we unpack the current key and value into variables.. If you need to get access to the index of the current iteration in a for loop, use the enumerate() function. # Using multiple variables in a For loop using enumerate() This is a three-step process: Use the enumerate() function to get access to the current index.; Use a for loop to iterate over the enumerate ...

  9. Assign the result of a loop to a variable in Python [duplicate]

    first I have to declare another var variable, which is silly but whatever. then, print var will return the last element of the list, which is "Paris", because the variable is overwritten for each iteration right. So my question is : how can I assign the output of my loop "i", for each iteration, to a variable in Python ?

  10. Python For Loop

    Syntax of for loop. for i in range/sequencee: statement 1 statement 2 statement n Code language: Python (python). In the syntax, i is the iterating variable, and the range specifies how many times the loop should run. For example, if a list contains 10 numbers then for loop will execute 10 times to print each number.; In each iteration of the loop, the variable i get the current value.

  11. How to Dynamically Declare Variables Inside a Loop in Python

    Then we name them x, y, and so on. The problem becomes more complicated when you need to declare variables dynamically in a loop. I came up with three ways to do this in Python. 1. Using the exec command. In the above program, I initially declared an empty dictionary and added the elements into the dictionary.

  12. Changing Variable Names With Python For Loops

    Using a for loop, it iterates through the original names, converts each name to lowercase, and appends the result to the list lowercase_names. Python3. # Changing Case of Variable Names. original_names = ["varOne", "VarTwo", "VarThree"] lowercase_names = [] for name in original_names: lowercase_name = name.lower()

  13. How to Use a for Loop for Multiple Variables in Python

    In this example, the items() method is used to retrieve the key-value pairs from the dict1 dictionary. The for loop iterates over these pairs, allowing you to access and print each key and its corresponding value.. Use the for Loop With the enumerate() Function for Multiple Assignments in a List in Python. The enumerate() function in Python is used to add a counter to an iterable and return it ...

  14. For Loop with Two Variables in Python

    There are three types of loops in python: For Loop: It is used to iterate over a sequence like a list, tuple, set, dictionary, or string. While Loop: It executes till the condition is True. Nested Loop: Loops can be nested which means a loop inside the other loop's body. For example: for loop inside a for loop, while loop inside the for loop ...

  15. python

    I'm trying to use a for loop to assign values to variables - in this case the variables are all called: 'die1', 'die2', 'die3', etc. ... Lists are very important, especially in Python, which has several powerful features for handling lists. When code has a bunch of numbered variables like die1, die2, ...

  16. 20. For Loops

    The for loop is used to go through each element in the performance_levels tuple one by one. In each iteration, the loop variable level will take on the value of the current element in the tuple.. Inside the loop, the print() function is used to display the current value of the level variable. This means that it will print each performance level to the screen, starting with "beginner," then ...

  17. How to Write a For Loop in Python

    Let's go over the syntax of the for loop: It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with ": ".

  18. The Walrus Operator: Python 3.8 Assignment Expressions

    Each new version of Python adds new features to the language. For Python 3.8, the biggest change is the addition of assignment expressions.Specifically, the := operator gives you a new syntax for assigning variables in the middle of expressions. This operator is colloquially known as the walrus operator.. This tutorial is an in-depth introduction to the walrus operator.

  19. How to assign variables in a for loop in Python

    0. var = records[i] What I want to do is to create a different variable for each list (for instance there are three lists in records so i want to assign each list to a different variable (3 variables since there are three lists)). However, it only prints the last list ( ["alpha", 50.0]) and only one variable is assigned (var).

  20. 3. An Informal Introduction to Python

    The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. ... The body of the loop is indented: indentation is Python's way of ...

  21. Assign variable in while loop condition in Python?

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) ( := operator), it's now possible to capture the condition value ( data.readline()) of the while loop as a variable ( line) in order to re-use it within the body of the loop: while line := data.readline(): do_smthg(line)

  22. Python if, if...else Statement (With Examples)

    Python if Statement. An if statement executes a block of code only if the specified condition is met.. Syntax. if condition: # body of if statement. Here, if the condition of the if statement is: . True - the body of the if statement executes.; False - the body of the if statement is skipped from execution.; Let's look at an example. Working of if Statement