Python Code Examples—Learn Python with 50+ Examples

Here is a list of Python code examples. This list covers the basics of Python. You can use this list as a cheat sheet whether you are preparing for an exam, interview, or are otherwise curious about Python.

Fundamentals of Python

Variables

A variable can store a value. The value can be a number, list, or anything else that is a valid Python object.

Here are some examples:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
number = 10
name = "Jack"
data = {"name": "Alice", age: 30}
numbers = [1, 2, 3, 4, 5]
number = 10 name = "Jack" data = {"name": "Alice", age: 30} numbers = [1, 2, 3, 4, 5]
number = 10
name = "Jack"
data = {"name": "Alice", age: 30}
numbers = [1, 2, 3, 4, 5]

Strings

Strings represent text in Python.

For example, you can create a variable that stores the name of a person:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
name = "Alice"
name = "Alice"
name = "Alice"

Numbers

Python supports numeric values, that is, integers and floats.

If a number has lots of digits, you can use underscores as visual separators to group digits.

Here are some examples of formatting numbers in Python:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
number = 6
ten_thousand = 10_000
billion = 1_000_000_000
decimal_number = 4.23
pi_approx = 3.142
earth_mass = 5.972e24
proton_mass = 1.6726e-27
number = 6 ten_thousand = 10_000 billion = 1_000_000_000 decimal_number = 4.23 pi_approx = 3.142 earth_mass = 5.972e24 proton_mass = 1.6726e-27
number = 6

ten_thousand = 10_000
billion = 1_000_000_000

decimal_number = 4.23
pi_approx = 3.142

earth_mass = 5.972e24
proton_mass = 1.6726e-27

Booleans

The boolean values True or False represent whether something is true or not true.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
is_raining = False
is_sunny = True
is_raining = False is_sunny = True
is_raining = False
is_sunny = True

Constants

Constants are variables that are not meant to change. To declare constants, make sure the name of the constant is capitalized.

For instance:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
NUM = 10
NAME = "Alice"
PARTICIPANTS = ["Alice", "Bob", "Charlie"]
NUM = 10 NAME = "Alice" PARTICIPANTS = ["Alice", "Bob", "Charlie"]
NUM = 10
NAME = "Alice"
PARTICIPANTS = ["Alice", "Bob", "Charlie"]

Comments

Leaving code comments is sometimes necessary.

Unfortunately, you cannot just type what you want in a code editor.

Instead, you need to highlight the fact that the line or lines contain a comment. The Python interpreter then knows that the line is not meant to be executed.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# This is a comment. It is marked by a '#'
# You can add one anywhere in the code.
'''
This is a docstring.
It can also be used as a
multi-line comment.
'''
# This is a comment. It is marked by a '#' # You can add one anywhere in the code. ''' This is a docstring. It can also be used as a multi-line comment. '''
# This is a comment. It is marked by a '#'
# You can add one anywhere in the code.

'''
This is a docstring.
It can also be used as a 
multi-line comment.
'''

Type Conversions

In Python, there are different types, such as integers, floats, and booleans.

You can convert from one type to another using the built-in conversion functions.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
num_string = "10"
num_int = int(num_string)
num_float = float(num_string)
num_string = "10" num_int = int(num_string) num_float = float(num_string)
num_string = "10"

num_int    = int(num_string)
num_float  = float(num_string)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
is_rainy = "True"
# Convert string to boolean
is_rainy = bool(is_rainy)
is_rainy = "True" # Convert string to boolean is_rainy = bool(is_rainy)
is_rainy = "True"

# Convert string to boolean
is_rainy = bool(is_rainy)

Python can also make automatic type conversion. For example, when you try to add an integer with a float, it converts the integer to float for you:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
num1 = 10
num2 = 12.32
res = num1 + num2
print(type(res))
num1 = 10 num2 = 12.32 res = num1 + num2 print(type(res))
num1 = 10
num2 = 12.32

res = num1 + num2

print(type(res))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<class 'float'>
<class 'float'>
<class 'float'>

Math Operators in Python

OperatorsOperationExample
**Exponent (Power)2 ** 4 = 16
%Modulus (Remainder)5 % 3 = 2
//Integer division20 // 7 = 2
/Division11 / 5 = 2.2
*Multiplication2 * 3 = 6
Subtraction4 - 3 = 1
+Addition1 + 1 = 2

Control Flow in Python

Comparison Operators in Python

OperatorMeaning
==Equal to
!=Not equal to
<Less than
>Greater Than
<=Less than or Equal to
>=Greater than or Equal to

Examples:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
5 == 5 # True
5 == 6 # False
1 < 2 # True
2 <= 1 # False
"Alice" == "Alice" # True
"Alice" == "Bob" # False
True == True # True
Flase == False # False
5 == 5 # True 5 == 6 # False 1 < 2 # True 2 <= 1 # False "Alice" == "Alice" # True "Alice" == "Bob" # False True == True # True Flase == False # False
5 == 5             # True
5 == 6             # False

1 < 2              # True
2 <= 1             # False

"Alice" == "Alice" # True
"Alice" == "Bob"   # False

True == True       # True
Flase == False     # False

If…Else Statements

If…else statements are used to check if a condition is true.

  • If the condition is met, a piece of code is executed.
  • If the condition is not met, another piece of code is executed instead.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
age = 20
if age <= 18:
print("You cannot drive")
else:
print("You are old enough to drive")
age = 20 if age <= 18: print("You cannot drive") else: print("You are old enough to drive")
age = 20

if age <= 18:
    print("You cannot drive")
else:
    print("You are old enough to drive")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
You are old enough to drive
You are old enough to drive
You are old enough to drive

If…Elif…Else Statements

If you have multiple conditions that you want to test at the same, you can add elif statements between the if...else.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
age = 17
if age < 17:
print("You cannot drive")
elif age == 17:
print("You can start at driving school")
else:
print("You are old enough to drive")
age = 17 if age < 17: print("You cannot drive") elif age == 17: print("You can start at driving school") else: print("You are old enough to drive")
age = 17

if age < 17:
    print("You cannot drive")
elif age == 17:
    print("You can start at driving school")
else:
    print("You are old enough to drive")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
You can start at driving school
You can start at driving school
You can start at driving school

Ternary Operator

In Python, there is a shorthand for if…else statements called the ternary operator.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
age = 50
# Regular if-else statement
description = ""
if age > 100:
description = "Old"
else:
description = "Young"
# The same using ternary operator as a shorthand
description = "Old" if age > 100 else "Young"
age = 50 # Regular if-else statement description = "" if age > 100: description = "Old" else: description = "Young" # The same using ternary operator as a shorthand description = "Old" if age > 100 else "Young"
age = 50

# Regular if-else statement
description = ""

if age > 100:
    description = "Old"
else:
    description = "Young"

# The same using ternary operator as a shorthand
description = "Old" if age > 100 else "Young"

For Loop

To repeat instructions, you can use a for loop in Python.

For example, if you want to print a list of numbers, you can use a for loop like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
1 2 3 4 5
1
2
3
4
5

While Loop

To repeat instructions, you can also use a while loop in Python.

For example, if you want to print a list of numbers, you can use a while loop:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
numbers = [1, 2, 3, 4, 5] i = 0 while i < len(numbers): print(numbers[i]) i += 1
numbers = [1, 2, 3, 4, 5]

i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
1 2 3 4 5
1
2
3
4
5

Break Statement

To exit a loop, you can use the break statement.

For example, let’s break the loop after finding a specific value:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1,4,3,2,5,19,5,0]
target = 3
for number in numbers:
print("Current number", number)
if number == target:
print("Target found. Exiting...")
break
numbers = [1,4,3,2,5,19,5,0] target = 3 for number in numbers: print("Current number", number) if number == target: print("Target found. Exiting...") break
numbers = [1,4,3,2,5,19,5,0]

target = 3

for number in numbers:
    print("Current number", number)
    if number == target:
        print("Target found. Exiting...")
        break

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Current number 1
Current number 4
Current number 3
Target found. Exiting...
Current number 1 Current number 4 Current number 3 Target found. Exiting...
Current number 1
Current number 4
Current number 3
Target found. Exiting...

Continue Statement

To end the current iteration of a loop, use the continue statement. This jumps directly to the next iteration and disregards whatever it was doing in the current iteration.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
n = 0
while n < 10:
n += 1
if n % 2 == 0:
continue
print(n)
n = 0 while n < 10: n += 1 if n % 2 == 0: continue print(n)
n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print(n)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
3
5
7
9
1 3 5 7 9
1
3
5
7
9

Pass Statement

To pass or skip the implementation in Python, use the pass statement.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def my_function():
pass
def my_function(): pass
def my_function():
    pass
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
for number in numbers:
pass
numbers = [1, 2, 3, 4, 5] for number in numbers: pass
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    pass

Functions in Python

A function is a labeled set of instructions that is easy to reuse. A function can take a number of parameters to work with.

The idea is then to call this function from other places in the code to perform the actions.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def greet(name):
print(f"Hello, {name}. Nice to meet you!")
greet("Alice")
greet("Bob")
def greet(name): print(f"Hello, {name}. Nice to meet you!") greet("Alice") greet("Bob")
def greet(name):
    print(f"Hello, {name}. Nice to meet you!")

greet("Alice")
greet("Bob")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello, Alice. Nice to meet you!
Hello, Bob. Nice to meet you!
Hello, Alice. Nice to meet you! Hello, Bob. Nice to meet you!
Hello, Alice. Nice to meet you!
Hello, Bob. Nice to meet you!

Python Function Default Parameters

A Python function can take default parameters. In other words, if the function is called without parameters, a default parameter is used instead.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def greet(name="there"):
print(f"Hello, {name}. Nice to meet you!")
greet()
greet("Bob")
def greet(name="there"): print(f"Hello, {name}. Nice to meet you!") greet() greet("Bob")
def greet(name="there"):
    print(f"Hello, {name}. Nice to meet you!")

greet()
greet("Bob")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello, there. Nice to meet you!
Hello, Bob. Nice to meet you!
Hello, there. Nice to meet you! Hello, Bob. Nice to meet you!
Hello, there. Nice to meet you!
Hello, Bob. Nice to meet you!

Python Function Keyword Arguments

In addition to passing function parameters as-is, you can label them. A labeled function argument is called a keyword argument.

Let’s see an example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def email(firstname, lastname):
print(f"{firstname.lower()}.{lastname.lower()}@codingem.com")
# Regular arguments
email("Alice", "Alisson")
# Keyword arguments
email(lastname="Alisson", firstname="Alice")
def email(firstname, lastname): print(f"{firstname.lower()}.{lastname.lower()}@codingem.com") # Regular arguments email("Alice", "Alisson") # Keyword arguments email(lastname="Alisson", firstname="Alice")
def email(firstname, lastname):
    print(f"{firstname.lower()}.{lastname.lower()}@codingem.com")

# Regular arguments
email("Alice", "Alisson")

# Keyword arguments
email(lastname="Alisson", firstname="Alice")

Both ways produce the same output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
alice.alisson@codingem.com
alice.alisson@codingem.com
alice.alisson@codingem.com alice.alisson@codingem.com
alice.alisson@codingem.com
alice.alisson@codingem.com

The *args Parameters

Allow any number of arguments to a function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def add(*args):
result = 0
for number in args:
result += number
return result
print(add(1, 2, 3))
print(add(1, 2, 3, 4, 5))
print(add(1))
def add(*args): result = 0 for number in args: result += number return result print(add(1, 2, 3)) print(add(1, 2, 3, 4, 5)) print(add(1))
def add(*args):
    result = 0
    for number in args:
        result += number
    return result


print(add(1, 2, 3))
print(add(1, 2, 3, 4, 5))
print(add(1))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
6
15
1
6 15 1
6
15
1

The **kwargs Parameters

Allow any number of keyword arguments into a function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def scan(**kwargs):
for item, brand in kwargs.items():
print(f"{item}: {brand}")
scan(shoes="Adidas", shirt="H&M", sweater="Zara")
scan(socks="Nike")
def scan(**kwargs): for item, brand in kwargs.items(): print(f"{item}: {brand}") scan(shoes="Adidas", shirt="H&M", sweater="Zara") scan(socks="Nike")
def scan(**kwargs):
    for item, brand in kwargs.items():
        print(f"{item}: {brand}")


scan(shoes="Adidas", shirt="H&M", sweater="Zara")
scan(socks="Nike")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
shoes: Adidas
shirt: H&M
sweater: Zara
socks: Nike
shoes: Adidas shirt: H&M sweater: Zara socks: Nike
shoes: Adidas
shirt: H&M
sweater: Zara

socks: Nike

Recursion

Recursion means a function calls itself inside the function.

For example, to calculate a factorial, you can use a recursive function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def factorial(n):
if n == 1:
return n
else:
# Function calls itself from within
return n * factorial(n - 1)
f = factorial(4)
# factorial(4) = 4! = 4 * 3 * 2 * 1 = 24
print(f)
def factorial(n): if n == 1: return n else: # Function calls itself from within return n * factorial(n - 1) f = factorial(4) # factorial(4) = 4! = 4 * 3 * 2 * 1 = 24 print(f)
def factorial(n):
    if n == 1:
        return n
    else:
        # Function calls itself from within
        return n * factorial(n - 1)

f = factorial(4)

# factorial(4) = 4! = 4 * 3 * 2 * 1 = 24
print(f)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
24
24
24

Lambda Functions

Lambda functions or lambda expressions are anonymous functions.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
five_squared = (lambda x: x ** 2)(5)
print(five_squared)
five_squared = (lambda x: x ** 2)(5) print(five_squared)
five_squared = (lambda x: x ** 2)(5)
print(five_squared)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
25
25
25

The above example is not useful other than it demonstrates how you can create a lambda.

Let’s see lambdas in real action:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_nums = filter(lambda n: n % 2 == 0, numbers)
print(list(even_nums))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_nums = filter(lambda n: n % 2 == 0, numbers) print(list(even_nums))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = filter(lambda n: n % 2 == 0, numbers)

print(list(even_nums))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

Function Docstrings

To document a function, you can write a docstring to describe what it does.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def sum(a, b):
""" Returns the sum of two numbers."""
return a + b
# Ask to see the docstring of a function:
help(sum)
def sum(a, b): """ Returns the sum of two numbers.""" return a + b # Ask to see the docstring of a function: help(sum)
def sum(a, b):
    """ Returns the sum of two numbers."""
    return a + b

# Ask to see the docstring of a function:
help(sum)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Help on function sum in module __main__:
sum(a, b)
Returns the sum of two numbers.
Help on function sum in module __main__: sum(a, b) Returns the sum of two numbers.
Help on function sum in module __main__:

sum(a, b)
    Returns the sum of two numbers.

Lists in Python

Lists are data structures that can hold multiple items at the same time. Lists in Python are easy to access, update, and modify.

Here are some examples:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
# Access elements of a list
first = numbers[0]
# Add new element to the end of a list
numbers.append(6)
# Remove the last element from a list
numbers.pop()
numbers = [1, 2, 3, 4, 5] # Access elements of a list first = numbers[0] # Add new element to the end of a list numbers.append(6) # Remove the last element from a list numbers.pop()
numbers = [1, 2, 3, 4, 5]

# Access elements of a list
first = numbers[0]

# Add new element to the end of a list
numbers.append(6)

# Remove the last element from a list
numbers.pop()

Sorting a List

Sort a list of numbers in increasing order:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]
numbers.sort()
print(numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2] numbers.sort() print(numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

numbers.sort()

print(numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[1, 2, 3, 3, 4, 7, 8, 9, 10]
[1, 2, 3, 3, 4, 7, 8, 9, 10]
[1, 2, 3, 3, 4, 7, 8, 9, 10]

And to sort it in decreasing order:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]
numbers.sort(reverse=True)
print(numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2] numbers.sort(reverse=True) print(numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

numbers.sort(reverse=True)

print(numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[10, 9, 8, 7, 4, 3, 3, 2, 1]
[10, 9, 8, 7, 4, 3, 3, 2, 1]
[10, 9, 8, 7, 4, 3, 3, 2, 1]

Sorting a List by Creating a Sorted Copy

To create a copy instead of sorting the list directly, use the sorted() function.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2] sorted_numbers = sorted(numbers) print(sorted_numbers)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

sorted_numbers = sorted(numbers)

print(sorted_numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[1, 2, 3, 3, 4, 7, 8, 9, 10]
[1, 2, 3, 3, 4, 7, 8, 9, 10]
[1, 2, 3, 3, 4, 7, 8, 9, 10]

Slicing a List

To get a slice of a list, use the : operator with square brackets and define the range.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]
subset = numbers[0:3]
print(subset)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2] subset = numbers[0:3] print(subset)
numbers = [8, 3, 1, 3, 4, 9, 10, 7, 2]

subset = numbers[0:3]
print(subset)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[8, 3, 1]
[8, 3, 1]
[8, 3, 1]

Check a quick guide to slicing in Python.

Unpacking a List

You can unpack or de-structure a Python list by assigning each item into a separate variable by:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
point = [0, 1, 2]
x, y, z = point
print(x)
print(y)
print(z)
point = [0, 1, 2] x, y, z = point print(x) print(y) print(z)
point = [0, 1, 2]

x, y, z = point

print(x)
print(y)
print(z)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
0
1
2
0 1 2
0
1
2

Iterating Over a List Using a For Loop

You can use a for loop to iterate over a list in Python.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
numbers = [1, 2, 3, 4, 5] for number in numbers: print(number)
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
1 2 3 4 5
1
2
3
4
5

Finding Index of a Specific Element

To figure out the index at which a specific element first occurs in a list, use the index() method:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
names = ["Alice", "Bob", "Charlie", "Bob", "David"]
bob_position = names.index("Bob")
print(f"Bob is first met at position {bob_position}")
names = ["Alice", "Bob", "Charlie", "Bob", "David"] bob_position = names.index("Bob") print(f"Bob is first met at position {bob_position}")
names = ["Alice", "Bob", "Charlie", "Bob", "David"]

bob_position = names.index("Bob")

print(f"Bob is first met at position {bob_position}")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Bob is first met at position 1
Bob is first met at position 1
Bob is first met at position 1

Iterables and Iterators

A for loop can be used to iterate over a list in Python like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
for number in numbers_list:
print(number)
numbers = [1, 2, 3, 4, 5] for number in numbers_list: print(number)
numbers = [1, 2, 3, 4, 5]

for number in numbers_list:
    print(number)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
1 2 3 4 5
1
2
3
4
5

Under the hood, the for loop grabs the iterator of the numbers list and calls next on it to get the next number.

This process looks like this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
numbers_iterator = iter(numbers)
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
numbers = [1, 2, 3, 4, 5] numbers_iterator = iter(numbers) print(next(numbers_iterator)) print(next(numbers_iterator)) print(next(numbers_iterator)) print(next(numbers_iterator)) print(next(numbers_iterator))
numbers = [1, 2, 3, 4, 5]

numbers_iterator = iter(numbers)

print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))
print(next(numbers_iterator))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
4
5
1 2 3 4 5
1
2
3
4
5

This describes how the for loop behaves under the hood.

Any iterable object in Python returns an iterator that can be used to iterate over that iterable.

Transform List Elements Using Map Function

To run an operation for each element of an iterable (such as a list), you can use the built-in map() function.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers))
numbers = [1, 2, 3, 4, 5] squared_numbers = map(lambda x: x ** 2, numbers) print(list(squared_numbers))
numbers = [1, 2, 3, 4, 5]

squared_numbers = map(lambda x: x ** 2, numbers)

print(list(squared_numbers))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

Filtering List Elements Using Filter Function

To filter list elements based on a condition, use the built-in filter() function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_nums = filter(lambda n: n % 2 == 0, numbers)
print(list(even_nums))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_nums = filter(lambda n: n % 2 == 0, numbers) print(list(even_nums))
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = filter(lambda n: n % 2 == 0, numbers)

print(list(even_nums))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]
[2, 4, 6, 8, 10]

Reducing List Elements Using Reduce Function

To accumulate a list by performing an operation on two consecutive elements use the functools reduce() function.

For example, let’s count the sum of list elements:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(f"The sum of numbers is {sum}")
from functools import reduce numbers = [1, 2, 3, 4, 5] sum = reduce(lambda x, y: x + y, numbers) print(f"The sum of numbers is {sum}")
from functools import reduce
numbers = [1, 2, 3, 4, 5]

sum = reduce(lambda x, y: x + y, numbers)

print(f"The sum of numbers is {sum}")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The sum of numbers is 15
The sum of numbers is 15
The sum of numbers is 15

List Comprehensions

You can use a list comprehension to shorten your for loops:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5]
squared_nums = [number ** 2 for number in numbers]
print(squared_nums)
numbers = [1, 2, 3, 4, 5] squared_nums = [number ** 2 for number in numbers] print(squared_nums)
numbers = [1, 2, 3, 4, 5]
squared_nums = [number ** 2 for number in numbers]

print(squared_nums)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

Another example with a condition:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_even_nums = [number ** 2 for number in numbers if number % 2 == 0]
print(squared_even_nums)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] squared_even_nums = [number ** 2 for number in numbers if number % 2 == 0] print(squared_even_nums)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_even_nums = [number ** 2 for number in numbers if number % 2 == 0]

print(squared_even_nums)

The result is all the even numbers squared. Odd numbers are left out:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]
[4, 16, 36, 64, 100]

Tuples in Python

A tuple is like a list that cannot be changed after creation. You can only create one and read values from it.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
names = ("Alice", "Bob", "Charlie")
first = names[0] # Returns "Alice"
names = ("Alice", "Bob", "Charlie") first = names[0] # Returns "Alice"
names = ("Alice", "Bob", "Charlie")

first = names[0] # Returns "Alice"

Unpacking Tuples

To read the values of a tuple into separate variables, you can use tuple unpacking:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
location = (0, 1, 3)
x, y, z = location
print(x)
print(y)
print(z)
location = (0, 1, 3) x, y, z = location print(x) print(y) print(z)
location = (0, 1, 3)

x, y, z = location

print(x)
print(y)
print(z)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
0
1
3
0 1 3
0
1
3

Dictionaries in Python

Python dictionaries hold key-value pairs of data.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
student = {
"name": "Alice",
"age": 30,
"major": "Physics",
"married": False,
"hobbies": ["Jogging", "Cycling", "Gym"]
}
student = { "name": "Alice", "age": 30, "major": "Physics", "married": False, "hobbies": ["Jogging", "Cycling", "Gym"] }
student = {
    "name": "Alice",
    "age": 30,
    "major": "Physics",
    "married": False,
    "hobbies": ["Jogging", "Cycling", "Gym"]
}

Now you can access the values of the dictionary. For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print(student["name"])
for hobby in student["hobbies"]:
print(f"I love {hobby}")
print(student["name"]) for hobby in student["hobbies"]: print(f"I love {hobby}")
print(student["name"])

for hobby in student["hobbies"]:
    print(f"I love {hobby}")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Alice
I love Jogging
I love Cycling
I love Gym
Alice I love Jogging I love Cycling I love Gym
Alice
I love Jogging
I love Cycling
I love Gym

Or you can change them:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Update an existing item
student["age"] = 31
# Add a new item
student["graduated"] = False
print(student)
# Update an existing item student["age"] = 31 # Add a new item student["graduated"] = False print(student)
# Update an existing item
student["age"] = 31

# Add a new item
student["graduated"] = False

print(student)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{'name': 'Alice', 'age': 31, 'major': 'Physics', 'married': False, 'hobbies': ['Jogging', 'Cycling', 'Gym'], 'graduated': False}
{'name': 'Alice', 'age': 31, 'major': 'Physics', 'married': False, 'hobbies': ['Jogging', 'Cycling', 'Gym'], 'graduated': False}
{'name': 'Alice', 'age': 31, 'major': 'Physics', 'married': False, 'hobbies': ['Jogging', 'Cycling', 'Gym'], 'graduated': False}

Dictionary Comprehension

To loop through a dictionary in Python, you can use a regular for loop. Or you can utilize dictionary comprehension.

To access the dictionary items for the loop, call the items() method of the dictionary.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
data = {"first": 1, "second": 2, "third": 3}
data_squared_values = {value ** 2 for key, value in data.items()}
print(data_squared_values)
data = {"first": 1, "second": 2, "third": 3} data_squared_values = {value ** 2 for key, value in data.items()} print(data_squared_values)
data = {"first": 1, "second": 2, "third": 3}

data_squared_values = {value ** 2 for key, value in data.items()}

print(data_squared_values)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{1, 4, 9}
{1, 4, 9}
{1, 4, 9}

Sets in Python

Sets are collections of unique values. In other words, a set cannot hold two identical values.

Here is an example of a set:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = {1, 2, 3, 3, 3, 3, 3, 2, 1, 1, 0}
# Each value can occur only once in a set
print(numbers)
numbers = {1, 2, 3, 3, 3, 3, 3, 2, 1, 1, 0} # Each value can occur only once in a set print(numbers)
numbers = {1, 2, 3, 3, 3, 3, 3, 2, 1, 1, 0}

# Each value can occur only once in a set
print(numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{0, 1, 2, 3}
{0, 1, 2, 3}
{0, 1, 2, 3}

Set Comprehension

To loop through a set, you can use a regular loop.

But you can also use a shorthand called set comprehension.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = {1, 2, 3, 4, 5}
squared_numbers = {number ** 2 for number in numbers}
print(squared_numbers)
numbers = {1, 2, 3, 4, 5} squared_numbers = {number ** 2 for number in numbers} print(squared_numbers)
numbers = {1, 2, 3, 4, 5}

squared_numbers = {number ** 2 for number in numbers}

print(squared_numbers)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{1, 4, 9, 16, 25}
{1, 4, 9, 16, 25}
{1, 4, 9, 16, 25}

Next, let’s take a look at the useful built-in methods of a set.

Union of Sets

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
union = numbers1.union(numbers2)
print(union)
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} union = numbers1.union(numbers2) print(union)
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

union = numbers1.union(numbers2)

print(union)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}

Intersection of Sets

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
intersection = numbers1.intersection(numbers2)
print(intersection)
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} intersection = numbers1.intersection(numbers2) print(intersection)
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

intersection = numbers1.intersection(numbers2)

print(intersection)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{3}
{3}
{3}

Difference between Sets

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
difference = numbers1.difference(numbers2)
print(difference)
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} difference = numbers1.difference(numbers2) print(difference)
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

difference = numbers1.difference(numbers2)

print(difference)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{1, 2}
{1, 2}
{1, 2}

Symmetric Difference of Sets

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
sym_difference = numbers1.symmetric_difference(numbers2)
print(sym_difference)
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} sym_difference = numbers1.symmetric_difference(numbers2) print(sym_difference)
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

sym_difference = numbers1.symmetric_difference(numbers2)

print(sym_difference)

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{1, 2, 4, 5}
{1, 2, 4, 5}
{1, 2, 4, 5}

Subset

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
print({1, 2}.issubset(numbers1))
print({1, 2}.issubset(numbers2))
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} print({1, 2}.issubset(numbers1)) print({1, 2}.issubset(numbers2))
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

print({1, 2}.issubset(numbers1))
print({1, 2}.issubset(numbers2))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
True
False
True False
True
False

Superset

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}
print({1, 2, 3, 4}.issuperset(numbers1))
print({1, 2, 3, 4}.issuperset(numbers2))
numbers1 = {1, 2, 3} numbers2 = {3, 4, 5} print({1, 2, 3, 4}.issuperset(numbers1)) print({1, 2, 3, 4}.issuperset(numbers2))
numbers1 = {1, 2, 3}
numbers2 = {3, 4, 5}

print({1, 2, 3, 4}.issuperset(numbers1))
print({1, 2, 3, 4}.issuperset(numbers2))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
True
False
True False
True
False

Disjoint Sets

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print({1, 2, 3}.isdisjoint({4, 5, 6}))
print({1, 2, 3}.isdisjoint({1, 100, 1000}))
print({1, 2, 3}.isdisjoint({4, 5, 6})) print({1, 2, 3}.isdisjoint({1, 100, 1000}))
print({1, 2, 3}.isdisjoint({4, 5, 6}))
print({1, 2, 3}.isdisjoint({1, 100, 1000}))

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
True
False
True False
True
False

Error Handling in Python

Try…Except Structure

The basic error handling in Python is possible by trying to run an expression and catching the possible error.

This can be done using the try…except structure.

For example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by 0")
except NameError:
print("Define both numbers first")
try: result = x / y except ZeroDivisionError: print("Cannot divide by 0") except NameError: print("Define both numbers first")
try:
    result = x / y
except ZeroDivisionError:
    print("Cannot divide by 0")
except NameError:
    print("Define both numbers first")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Define both numbers first
Define both numbers first
Define both numbers first

Try…Except…Finally Structure

To always run a block of code after handling errors, use a finally block:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
y = 10
print(y)
except:
print("There was an error")
finally:
print("Process completed.")
try: y = 10 print(y) except: print("There was an error") finally: print("Process completed.")
try:
    y = 10
    print(y)
except:
    print("There was an error")
finally:
    print("Process completed.")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The number is 10
Process completed.
The number is 10 Process completed.
The number is 10
Process completed.

Try…Except…Else Structure

You can run code if there are no errors in the expression you run in the try block using the else statement.

For instance:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try:
y = 10
print(y)
except:
print("There was an error")
else:
print("There were no errors.")
finally:
print("Process completed.")
try: y = 10 print(y) except: print("There was an error") else: print("There were no errors.") finally: print("Process completed.")
try:
    y = 10
    print(y)
except:
    print("There was an error")
else:
    print("There were no errors.")
finally:
    print("Process completed.")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
The number is 10
There were no errors.
Process completed.
The number is 10 There were no errors. Process completed.
The number is 10
There were no errors.
Process completed.

Python Loops with Else

For…Else

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3]
for n in numbers:
print(n)
else:
print("Loop completed")
numbers = [1, 2, 3] for n in numbers: print(n) else: print("Loop completed")
numbers = [1, 2, 3]

for n in numbers:
    print(n)
else:
    print("Loop completed")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
Loop completed
1 2 3 Loop completed
1
2
3
Loop completed

While…Else

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [1, 2, 3]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
else:
print("Loop completed")
numbers = [1, 2, 3] i = 0 while i < len(numbers): print(numbers[i]) i += 1 else: print("Loop completed")
numbers = [1, 2, 3]

i = 0
while i < len(numbers):
    print(numbers[i])
    i += 1
else:
    print("Loop completed")

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
1
2
3
Loop completed
1 2 3 Loop completed
1
2
3
Loop completed

Files in Python

Read a Text File

To read a text file, use the following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
with open('example.txt') as file:
lines = file.readlines()
with open('example.txt') as file: lines = file.readlines()
with open('example.txt') as file:
    lines = file.readlines()

If the file is not in the same folder as your code, remember to replace the example.txt with the path to the file.

Write to a Text File

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
with open('example.txt', 'w') as f:
f.write('Hello world!')
with open('example.txt', 'w') as f: f.write('Hello world!')
with open('example.txt', 'w') as f:
    f.write('Hello world!')

If you want to create a file, use the same syntax. If the file it tries to open does not exist, a new one is created.

If you want to create a file to another folder, replace the example.txt with the desired path to the file.

Check If a File Exists

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from os.path import exists
if exists(path_to_file):
# Do something
from os.path import exists if exists(path_to_file): # Do something
from os.path import exists

if exists(path_to_file):
    # Do something

Conclusion

That is a lot of Python code examples. I hope you find it useful.

Happy coding!

Further Reading

Python Interview Questions and Answers

Useful Advanced Features of Python