Use for Loop That Loops Over a Sequence in Python
Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, set, String, etc. A sequence consists of multiple items and this item can be iterated using in keyword and range keyword in for loop.
Example 1: Python For Loop using List
A list is used to store the multiple values of the different types under a single variable. It is mutable i.e., items in the list can be changed after creation. The list is created by enclosing the data items with square brackets.
# list creation
a = ["Geeks", "for", "Geeks"]
for i in a:
print(i)
print('-----')
for i in range(len(a)):
print(a[i])
Output
Geeks for Geeks ----- Geeks for Geeks
Example 2: Python For Loop using Tuple
A tuple is used to store the multiple values of the different types under a single variable. It is immutable i.e., items in a tuple cannot be changed after creation. A tuple is created by enclosing the data items with round brackets.
# tuple creation
tup = ("Geeks", "for", "Geeks",
"GFG", "Learning", "Portal")
for i in tup:
print(i)
print('-----')
for i in range(3, len(tup)):
print(tup[i])
Output
Geeks for Geeks GFG Learning Portal ----- GFG Learning Portal
Example 3: Python For Loop using Dictionary
Dictionary is an unordered collection of items where data is stored in key-value pairs. Unlike other data types like list, set and tuple it holds data as key: value pair. for loop uses in keyword to iterate over each value in a dictionary.
# dictionary creation
d = {1: "a", 2: "b", 3: "c", 4: "d"}
for i in d:
print(i)
Output
1 2 3 4
Example 4: Python For Loop using Set
A set is an unordered, unindexed, and immutable datatype that holds multiple values under a single variable. It can be created by surrounding the data items around flower braces or a set method. As the set is unindexed range method is not used.
# set creation
set1 = {"unordered", "unindexed", "immutable"}
for i in set1:
print(i)
Output
unordered unindexed immutable
Example 5: Python For Loop using String
Here we passed the step variable as 2 in the range method. So we got alternate characters in a string.
# string creation
str = "GFG Learning-Portal"
for i in str:
print(i, end="")
print()
for i in range(0, len(str), 2):
print(str[i], end="_")
Output
GFG Learning-Portal G_G_L_a_n_n_-_o_t_l_