w3resource

Python for loop

Introduction to the for Loop

In Python, the for loop is used to iterate over elements of a sequence (such as lists, strings, tuples, etc.). Unlike languages like C or Pascal, where for loops are used to iterate over a range of numbers, Python's for loop is more versatile, allowing you to iterate over any iterable object, such as lists, dictionaries, and strings.

Syntax of a for Loop

for variable_name in sequence :
    statement_1
    statement_2
    ....

Parameter:

Name Description
variable_name The variable that takes the value of each item in the sequence during each iteration of the loop.
sequence A sequence of values that will be assigned to the target variable variable_name. Values are provided using a list or a string or from the built-in function range().
statement_1, statement_2 ..... The block of code to be executed for each item in the sequence.

Example: Iterating over a List

>>> #The list has four elements, indices start at 0 and end at 3
>>> color_list = ["Red", "Blue", "Green", "Black"]
>>> for c in color_list:
        print(c)

  Red
  Blue
  Green
  Black
>>>

In this example, ‘color_list’ contains a sequence of color names. The for loop assigns the first item ("Red") to the variable c, then executes the print(c) statement. This process repeats for each item in the list until all items are printed.

Python for loop and range() function

The range() function returns a list of consecutive integers. The function has one, two or three parameters where last two parameters are optional. It is widely used in for loops. Here is the syntax.

range(a)
range(a,b)
range(a,b,c)

range(a) : Generates numbers from 0 to a-1

Syntax:

for <variable> in range(<number>): 

Example:

>>> for a in range(4):
  print(a)
 
  0
  1
  2
  3
>>>

range(a,b): Generates numbers from a to b-1, incrementing by 1.

Syntax:

for "variable" in range("start_number", "end_number"):

Example:

>>> for a in range(2,7):
 print(a)

  2
  3
  4
  5
  6
>>>

range(a,b,c): Generates numbers from a to b-1, incrementing by c.

Example:

>>> for a in range(2,19,5):
  print(a)
 
 2
 7
 12 
 17
>>>

Python for loop: Iterating over different Data Structures

Example: Iterating over tuple

In this example, we count the number of even and odd numbers from a tuple.

numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
        if x % 2:
    	     count_odd+=1
        else:
    	     count_even+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)

Output:

Number of even numbers:4
Number of odd numbers: 5

In the above example a tuple named numbers is declared which holds the integers 1 to 9.

The best way to check if a given number is even or odd is to use the modulus operator (%).
The operator returns the remainder when dividing two numbers.
Modulus of 8 % 2 returns 0 as 8 is divided by 2, therefore 8 is even and modulus of 5 % 2 returns 1 therefore 5 is odd.

The for loop iterates through the tuple and we test modulus of x % 2 is true or not, for every item in the tuple and the process will continue until we rich the end of the tuple.
When it is true count_even increase by one otherwise count_odd is increased by one.
Finally, we print the number of even and odd numbers through print statements.

Example: Iterating over list

In the following example, the for loop iterates through a list and prints each item along with its type:

datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
   print ("Type of ",item, " is ", type(item))

Output:

Type of  1452  is  <class 'int'>
Type of  11.23  is  <class 'float'>
Type of  (1+2j)  is  <class 'complex'>
Type of  True  is  <class 'bool'>
Type of  w3resource  is  <class 'str'>
Type of  (0, -1)  is  <class 'tuple'>
Type of  [5, 12]  is  <class 'list'>
Type of  {'section': 'A', 'class': 'V'}  is  <class 'dict'>

Example: Iterating over dictionary

You can use a for loop to iterate over the keys and values of a dictionary.

>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
>>> for key in color:
   print(key)
 
c2
c1
c3
>>>

Following for loop iterates through its values :

>>> color = {"c1": "Red", "c2": "Green", "c3": "Orange"}
>>> for value in color.values():
   print(value)

Green
Red
Orange
>>>

Using an else Clause with a for Loop

Python allows you to use an else block with a for loop. The else block is executed after the for loop finishes, unless a break statement is encountered.

Syntax:

for variable_name in sequence :
    statement_1 
    statement_2
    ....
else :
    statement_3 
    statement_4
    ....

In this example, the else block runs after the loop completes its iterations. However, if the loop encounters a break, the else block will not execute.

Previous: Python If elif else
Next: Python While Loop

Test your Python skills with w3resource's quiz



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python/python-for-loop.php