Last modified: Jan 11, 2023 By Alexander Williams

Python: for x in variable

The "for x in variable" is one of the questions that beginners typed on google search. Therefore, in this article, we'll iterate over all Python data types.

Iterate Over a string variable

In python, the string represents a sequence of characters.

We'll iterate over a string variable in the following example:

# String
string = "Hello Python"

# Iterate Over
for x in string:
    print(x)

Output:

H
e
l
l
o
 
P
y
t
h
o
n

As we can see, the program prints character one by one.

Iterate Over an integer variable

An Integer is a whole number that can be positive or negative.

Let's try to iterate over a number and see the output.

# int
integer = 2022

# Iterate Over
for x in integer:
    print(x)

Output:

TypeError: 'int' object is not iterable

As you can see we got an error.

Logically, integers are not iterable. but we can iterate over it by converting the integer to a string by using the str() method.

integer = 2022

# Iterate Over
for x in str(integer):
    print(x)

Output:

2
0
2
2

Iterate Over a list variable

A list is used to store multiple items in a single variable.

Let's see how to iterate over a list.

# List
my_list = ["a", "b", "c"]

# Iterate Over
for x in my_list:
    print(x)

Output:

a
b
c

Iterate Over a tuple variable

The tuple is like a list the difference between them is that we can not append, modify or remove items' tuple.

# Tuple
my_tuple = ("a", "b", "c")

# Iterate Over
for x in my_tuple:
    print(x)

Output:

a
b
c

Iterate Over a set variable

The set is like a list but the set returns unordered items.

# Set
my_set = {"a", "b", "c"}

# Iterate Over
for x in my_set:
    print(x)

Output:

b
c
a

As demonstrated the items are not ordered.

Iterate Over a dictionary variable

the dictionary is data stored in key and value pairs.

Iterate over a dictionary is different than all examples that we have seen. Let's see how to Iterate over a dictionary:

# Dictionary
my_dic = {'Color': 'Blue', 'Fruit': 'Orange', 'Pet': 'Cat'}

# Iterate Over
for k, v in my_dic.items():
    print(k, v)

Output::

Color Blue
Fruit Orange
Pet Cat