Python for Loop

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.

Example

Print each fruit in a fruit list:

 
fruits = ["apple", "banana", "cherry"]
for 
  x in fruits:

	 
	print(x)

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:

Example

Loop through the letters in the word "banana":

 
for x in "banana":
  print(x)

The break Statement

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

Example

Exit the loop when x is "banana":

 
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  
  if x == 
  "banana":
    break

Example

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

 
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == 
  "banana":
    break
  print(x)

loops in python

Python programming language provides following types of loops to handle looping requirements. Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.

Syntax :

 while expression:
    statement(s)

        3. All the statements indented by the same number of character spaces after a programming construct are considered to be             part of a single block of code. Python uses indentation as its method of grouping statements.             Example: 

Output: 

 Hello Geek
Hello Geek
Hello Geek

Output: 

 Hello Geek
Hello Geek
Hello Geek
In Else Block

Syntax:

 for iterator_var in sequence:
    statements(s)

It can be used to iterate over a range and iterators.

 # Python program to illustrate
# Iterating over range 0 to n-1
 
n =4
fori inrange(0, n):
    print(i)

Output :

 0
1
2
3

Output: 

 List Iteration
geeks
for
geeks

Tuple Iteration
geeks
for
geeks

String Iteration
G
e
e
k
s

Dictionary Iteration
xyz  123
abc  345

Iterating by index of sequences: We can also use the index of elements in the sequence to iterate. The key idea is to first calculate the length of the list and in iterate over the sequence within the range of this length. See the below example: 

For more, checkout W3Schools and Geeks For Geeks.