Python Basics CheatSheet

  • linkedin
  • facebook
  • twitter
  • mail

This Python cheat sheet provides a comprehensive overview of various concepts like variables, data types, operators, conditional statements, loops, functions, and more. It also covers advanced topics such as object-oriented programming and exception handling.

Python Basics CheatSheet

Python Introduction

Python is a powerful programming language widely used in web development, data analysis, artificial intelligence, scientific computation, and automation.

Because of its easy syntax, Python is one of the most popular languages in 2022.

Hello World Program in Python

# print Hello World on the screen
print('Hello World')

# Output: Hello World

Python Print Output

1. You can use the print() function to print output in Python.

# print text
print('Hello, how are you?')
# Output: Hello, how are you?

# print numbers
print(43)
# Output: 43

2. You can pass multiple arguments to the print() function, separated by commas.

print('Hello,', 'how are you?')

# Output: Hello, how are you?

Here, arguments are printed on the same line, with a space between them.

3. To print text on multiple lines, you can use the newline character \n.

print('Hello, \nhow are you?')

# Output:
# Hello,
# how are you?

4. To print the result of an expression, you can pass the expression as an argument to print().

print( 9 + 11)
# Output: 20

print(12 / 4)
# Output: 3.0

print(3**2)
# Output: 9

Data Types

Python has 3 most common primitive data types:

1. Integer (int): represents positive or negative whole numbers, such as 12, -6, 0, and 100.

print(12)
# Output: 12

print(-6)
# Output: -6

print(0)
# Output: 0

2. Floating point (float): represents real numbers, such as 3.14, -32.6, and 0.0.

print(3.14)
# Output: 3.14

print(-32.6)
# Output: -32.6

print(0.0)
# Output: 0.0

3. String (str): represents a sequence of characters, such as 'Hello World' or "How are you?".

# string value using single quotes
print('Hello World')
# Output: Hello World

# string value using double quotes
print("How are you?")
# Output: How are you?

You can use either single quotes or double quotes to represent strings.


Variables

A variable is a named location in memory that stores a value. In Python, you don't need to specify the type of a variable when declaring it.

Based on the value you assign to a variable, the type will be automatically determined.

To declare a variable, you simply need to give it a name and assign a value to it using the = operator.

# declare a variable with an integer value
age = 25

# declare a variable with a float value
salary = 52978.84

# declare a variable with a string value
name = "Smith"

Print Variables

1. To print variables, you can pass them as arguments to the print() function.

age = 25
print(age)

salary = 52978.84
print(salary)

name = "Smith"
print(name)

# Output:
# 25
# 52978.84
# Smith

2. You can also print variables as a part of string

age = 25
salary = 52978.84
name = "Smith"

print("I am", name, "(", age, "years old developer), with annual salary of", salary)

# Output: I am Smith ( 25 years old developer), with annual salary of 52978.84

Data Types of Variables

You can use the type() function to check the data type of a variable.

age = 25
print(type(age))
# Output: <class 'int'>

salary = 52978.84
print(type(salary))
# Output: <class 'float'>

name = "Smith"
print(type(name))
# Output: <class 'str'>

Naming Python Variables

  • Variable names can only contain letters, digits, and underscores. They must start with a letter or an underscore
  • Variables are case sensitive; Name and name are two different variables.
  • You can't use Python keywords and built-in function names as variable names.
  • Use descriptive and meaningful names.
  • Use snake_case (all lowercase with underscores) for naming variables.
Illegal Variable Names Legal Variable Names
1st_student, student-info first_student, student_info
for, class, if name, age, PI, _name
first name first_name, basic_monthly_salary

Python Input

1. To read input from the user in Python, you can use the input() function.

name = input("Enter your name: ")
print("Name:", name)

# Output:
# Enter your name: Smith
# Name: Smith

2. The input() function reads input from the user as a string.

age = input("Enter your age: ")
print(type(age))

salary = input("Enter your salary: ")
print(type(salary))

# Output:
# Enter your age: 25
# <class 'str'>
# Enter your salary: 5643.46
# <class 'str'>

3. If you want to get number inputs, you can use the int() or float() function to convert the string to an integer or a floating point number, respectively.

age = int(input("Enter your age: "))
print(type(age))

salary = float(input("Enter your salary: "))
print(type(salary))

# Output:
# Enter your age: 25
# <class 'int'>
# Enter your salary: 5643.46
# <class 'float'>

Python Operators

An operator is a special symbol that carries out operations on values and variables. For example, the + operator performs an addition between two values.

result = 5 + 4
print(result)    # Output: 9

a = 32
b = 18
print(a + b)    # Output: 50

Different Types of Python Operators:

  1. Arithmetic Operators
  2. Comparison Operators
  3. Assignment Operators
  4. Logical Operators
  5. Bitwise Operators

Arithmetic operators

Python supports the following arithmetic operators:

+ (addition): adds two values or variables

a = 32
b = 18

print(a + b)    # Output: 50

- (subtraction): subtracts two values or variables

a = 32
b = 18

print(a - b)    # Output: 14

* (multiplication): multiple two values or variables

a = 3
b = 8

print(a * b)    # Output: 24

/ (division): divides two numbers and returns a floating point result

a = 32
b = 5

print(a / b)    # Output: 6.4

// (floor division): divides two numbers and returns the integer floor result

a = 32
b = 5

print(a // b)    # Output: 6

% (remainder): returns the remainder of the division of two values or variables

a = 32
b = 5

print(a % b)    # Output: 2

** (exponentiation): raises a number to the power of another

a = 3
b = 4

print(a ** b)    # Output: 81

Operator Precedence

The arithmetic operators have a defined order of precedence, that specifies which operator will be executed first if there exist multiple operators in a single expression. For example,

result = 2 ** 3 + 10 / 5
print(result)    # Output: 10.0

# ** is executed first, followed by / and then +

Order of operator precedence from highest to lowest:

  • **
  • *, /, //
  • +, -

You can use parentheses to change the order of precedence and specify which operations should be performed first.

result = 2 ** (3 + (10 / 5))
print(result)    # Output: 32.0

# / will be executed first, followed by + and then **

Assignment Operators

Python supports the following assignment operators:

= (assignment): assign a value to a variable

age = 25
name = 'Smith'

print(age)    # 25
print(name)    # Output: Smith

+= (addition assignment): adds the right operand to the left operand and assigns the result to the left operand

number = 12

# equivalent to number = number + 8
number += 8
print(number)    # Output: 20

-= (subtraction assignment): subtracts the right operand from the left operand and assigns the result to the left operand

number = 12

# equivalent to number = number - 8
number -= 8
print(number)    # Output: 4

*= (multiplication assignment): multiplies the left operand by the right operand and assigns the result to the left operand

number = 12

# equivalent to number = number * 8
number *= 8
print(number)    # Output: 96

/= (division assignment): divides the left operand by the right operand and assigns the result to the left operand

number = 12

# equivalent to number = number / 8
number /= 8
print(number)    # Output: 1.5

//= (floor division assignment): divides the left operand by the right operand and assigns the integer floor result to the left operand

number = 12

# equivalent to number = number // 8
number //= 8
print(number)    # Output: 1

%= (remainder assignment): divides the left operand by the right operand and assigns the remainder after division to the left operand

number = 12

# equivalent to number = number % 8
number %= 8
print(number)    # Output: 4

**= (exponentiation assignment): raises the left operand to the power of the right operand and assigns result to the left operand

number = 2

# equivalent to number = number ** 8
number **= 8
print(number)    # Output: 256

Boolean in Python

Boolean data type (bool) in Python represents one of two values: True or False.

a = True
b = False

print(a)    # Output: True
print(b)    # Output: False

You can use the bool() function to convert a value or a variable to a boolean. The function returns

  • False - for 0 or empty string
  • True - for any number or string
# convert integers to boolean
a = bool(1)
b = bool(0)

print(a)    # Output: True
print(b)    # Output: False

# convert string to boolean
a = bool("Hello")
b = bool("")

print(a)    # Output: True
print(b)    # Output: False

Comparison Operators

Python supports the following comparison operators:

== (equal to): checks if two values or variables are equal

a = 20
b = 30

print(a == b)    # Output: False

!= (not equal to): checks if two values or variables are not equal

a = 20
b = 30

print(a != b)    # Output: True

< (less than): checks if the value on the left is less than the value on the right

a = 20
b = 30

print(a < b)    # Output: True

<= (less than or equal to): checks if the value on the left is less than or equal to the value on the right

a = 20
b = 30

print(a <= b)    # Output: True

> (greater than): checks if the value on the left is greater than the value on the right

a = 20
b = 30

print(a > b)    # Output: False

>= (greater than or equal to): checks if the value on the left is greater than the value on the right

a = 20
b = 30

print(a >= b)    # Output: False

Logical Operators

Python supports the following logical operators:

and (Logical AND): returns True if both operands are True, else returns False

a = 30
b = 20
c = 10

result = (a > b) and (a > c)
print(result)    # Output: True

result = (a > b) and (a < c)
print(result)    # Output: False

Here,

  • (a > b) and (a > c) returns True because both expressions are True.
  • (a > b) and ( a < c) returns False because a < c is False.

or (Logical OR): returns True if at least one operand is True, else returns False

a = 30
b = 20
c = 10

result = (a < b) or (a < c)
print(result)    # Output: False

result = (a > b) or (a < c)
print(result)    # Output: True

Here,

  • (a < b) or (a < c) returns False because both expressions are False.
  • (a > b) or (a < c) returns True because a > b is True.

not (Logical NOT): returns True if the operand is False, False if the operand is True

a = 30
b = 20

result = not (a < b)
print(result)    # Output: True

result = not (a > b)
print(result)    # Output: False

Here,

  • not (a < b) returns True because a < b is False.
  • not (a > b) returns False because a > b is True.

Python Conditional Statements

Conditional statements allow us to control the flow of our program. They will execute one block of code under one condition and another block of code under different conditions.

Different types of conditional statements available in Python are:

  • if
  • if...else
  • if...elif...else
  • match...case

if Statement

The if statement executes a block of code only if a certain condition is True.

Syntax:

if condition:
    # block of code

Example: when condition is True

age = 19

# condition is True, so the if block is executed
if age >= 18:
    print('You can vote.')

print('End of if')

# Output:
# You can vote.
# End of if

Example: when condition is False

age = 16

# condition is False, so the if block is skipped
if age >= 18:
    print('You can vote.')

print('End of if')

# Output:
# End of if

if...else Statement

The if...else statement executes a block of code when the condition is True and another block of code when the condition is False.

Syntax:

if condition:
    # code block when condition is True
else:
    # code block when condition is False

Example: when condition is True

age = 19

# condition is True, so the if block is executed
if age >= 18:
    print('You can vote.')
else:
    print('You cannot vote.')

print('End of if...else')

# Output:
# You can vote.
# End of if...else

Example: when condition is False

age = 17

# condition is False, so the else block is executed
if age >= 18:
    print('You can vote.')
else:
    print('You cannot vote.')

print('End of if...else')

# Output:
# You cannot vote.
# End of if...else

elif Statement

The elif statement adds additional conditions when we have to make a choice from more than 2 options.

Syntax

if condition1:
    # code block when condition1 is True

elif condition2:
    # code block when condition2 is True
    
elif condition3:
    # code block when condition3 is True

....

else:
    # code block when all conditions are False

Example: when first condition is True

number = 3

if number > 0:
    print('Positive Number')
elif number < 0:
    print('Negative Number')
else:
    print('Zero Number')

# Output: Positive Number

Example: when second condition is True

number = -3

if number > 0:
    print('Positive Number')
elif number < 0:
    print('Negative Number')
else:
    print('Zero Number')

# Output: Negative Number

Example: when all conditions are False

number = 0

if number > 0:
    print('Positive Number')
elif number < 0:
    print('Negative Number')
else:
    print('Zero Number')

# Output: Negative Number

Nested if...else

We can use an if...else statement inside another if...else statement to create nested conditions, known as a nested if...else statement.

Syntax:

if condition1:
    # code block if condition1 is True
    if condition2:
        # code block if condition2 is True
    else:
        # code block if condition2 is False
else:
    # code block if condition1 is True

Example: when both outer and inner conditions are True

a = 4

if a > 0:
    if a % 2 == 0:
        print('Positive Even Number')
    else:
        print('Positive Odd Number')
else:
    print('Negative Number')
    
# Output: Positive Even Number

Here,

  • the outer condition a > 0 is True
  • the inner condition a % 2 == 0 is True

Since both conditions are True, the code block inside the nested if statement is executed.

Example: when outer condition is True and inner condition is False

a = 5

if a > 0:
    if a % 2 == 0:
        print('Positive Even Number')
    else:
        print('Positive Odd Number')
else:
    print('Negative Number')
    
# Output: Positive Odd Number

Here,

  • the outer condition a > 0 is True
  • the inner condition a % 2 == 0 is False

Since, the inner condition is False, the code block of the nested else statement is executed.

Example: when both inner and outer conditions are False

a = -3

if a > 0:
    if a % 2 == 0:
        print('Positive Even Number')
    else:
        print('Positive Odd Number')
else:
    print('Negative Number')
    
# Output: Negative Number

Here, the outer condition a > 0 is False, so the code block of the outer else statement is executed.


match...case Statement

The match...case statement executes a block of code among many alternatives. It is similar to the switch...case statement in other programming languages.

Syntax:

match expression:
    case value1:
        # code block if expression matches with value1
    case value:
        # code block if expression matches with value2
    case value3:
        # code block if expression matches with value3
    
    ...
    
    case other:
        # code block if expression matches with any cases

Example:

day = 3

match day:
    case 1:
        print('Sunday')
    case 2:
        print('Monday')
    case 3:
        print('Tuesday')
    case 3:
        print('Wednesday')
    case 4:
        print('Thursday')
    case 5:
        print('Friday')
    case 6:
        print('Saturday')
        
# Output: Tuesday

Here, the value of day is 3, which matches with case 3. Hence, we get Tuesday as output.


Python Loop

In Python, loops allow us to execute a block of code multiple times. For example, if you want to print a line of text 100 times, rather than typing the same code 100 times, we can use a loop to perform this task.

Types of Loops:

  • while Loop
  • for Loop

while Loop

The while loop executes a block of code repeatedly as long as the specified condition is True.

Syntax:

while condition:
    # code block to execute if condition is True

Example:

i = 1

while i < 6:
    print(i)
    i += 1
    
# Output: 1 2 3 4 5 

Multiplication table using a while loop

number = 4
i = 1

while i <= 10:
    print(number, '*', i, '=', number * i)
    i += 1

for Loop

The for loop allows us to iterate over a sequence (such as strings, lists, or tuples).

Syntax:

for item in sequence:
    # code block to execute

Example: with a string

text = 'python'

for character in text:
    print(character)

Here, the loop iterates through each character of the string and prints it.

Example: with a list

numbers = [1, 2, 3, 4, 5]

for item in numbers:
    print(item)

Here, the loop prints each element of the list.


break with Loop

We can use the break statement to immediately terminate the loop. It is generally used with if...else statements.

Syntax:

while condition:
    # code to execute
    if condition:
        break

Example: break with a while loop

i = 0

while i < 5:
    i += 1    
    if i == 3:
        break    
    print(i)

# Output:
# 1
# 2

Here, the loop terminates when the value of i becomes 3.

Example: break with a for loop

fruits = ['apple', 'banana', 'carrot', 'mango']

for item in fruits:
    if item == 'carrot':
        break
    print(item)

# Output:
# apple
# banana

Here, the loop terminates when the iteration reaches to the third element (value of item becomes carrot)


continue Statement

We can use the continue statement to skip the current iteration of the loop. It is generally used with if...else statements.

Syntax:

while condition:
    # code to execute
    if condition:
        continue

Example: continue with a while loop

i = 0

while i < 5:
    i += 1    
    if i == 3:
        continue 
    print(i)

# Output:
# 1
# 2
# 4
# 5

Here, the loop skips the iteration when the value of i becomes 3, hence it is not printed.

Example: continue with a for loop

fruits = ['apple', 'banana', 'carrot', 'mango']

for item in fruits:
    
    if item == 'carrot':
        continue
    
    print(item)

# Output:
# apple
# banana
# mango

Here, the loop skips the iteration when the value of item becomes carrot, hence it is not printed.


Infinite Loop

An infinite loop is a loop that repeats infinitely because the loop condition is always True. For example,

while True:
    print('Infinite Loop')

Note: Be careful while using infinite loops, as they can consume a lot of resources and cause your program to crash.


Loop with else

1. while Loop with else

You can also use an else statement along with a while loop, which will be executed once the loop is completed. For example,

i = 1

while i < 6:
    print(i)
    i += 1
else:
    print('Loop Execution Completed')

Output

1
2
3
4
Loop Execution Completed

You can see the else block is executed once the loop ends. However, if the loop is exited using the break statement, the else block is not executed. For example,

i = 1

while i < 6:
    
    if i == 3:
        break
    
    print(i)
    i += 1
else:
    print('Loop Execution Completed')

Output

1
2

This time the break statement terminates the loop, hence the else block is not executed.

2. for Loop with else

Similarly, we can also use the else block with a for loop. For example,

numbers = [1, 2, 3, 4, 5]

for item in numbers:
    print(item)
    
else:
    print('Loop execution completed')

Here, the else block will be executed once the execution of for loop is completed.


for Loop with else

The else part of the for loop is executed once all the items in the sequence exhaust.

Example

my_list = [5, "Hello"]

for item in my_list:
  print(item)

# executes else when all the items of the my_list exhaust
else:
    print("Inside else")

Output

5
Hello
Inside else

Python Functions

Python functions allow us to divide our code into smaller chunks that perform specific tasks. They help us reuse the same code again and again as per our needs.

1. Define Function

We use the def keyword to define a new function in Python.

def greet():
    print('Good Morning')

2. Call Function

Defining a function is not enough, we need to call it to execute a function. To call a function, we use the function name followed by parentheses.

greet()

Example:

# function definition
def greet():
    print('Good Morning')

# function call
greet()

# Output: Good Morning

Function Parameters

We can also pass values into a function, known as function parameters. These parameters can be used inside the function to perform some actions.

def greet(name):
    print('Good Morning,', name)

Here, name is a parameter we are using to personalize our greeting.

Call Function with Parameter

If a function accepts parameters, we need to pass some values (known as arguments) while calling the function.

# function with a parameter
def greet(name):
    print('Good Morning,', name)

# function calls with arguments
greet('Maria')
greet('Smith')

# Output:
# Good Morning, Maria
# Good Morning, Smith

Here, we are reusing the same function two times to greet Maria and Smith.

Function with multiple parameters

# function with 2 parameters
def add_numbers(number1, number2):
    sum = number1 + number2
    print(sum)
    
# function call with 2 arguments
add_numbers(12, 8)     # Output: 20
add_numbers(47, 38)    # Output: 85

Function Return Value

Similar to passing values to a function, we can also return values from a function. For this, we use the return keyword inside the function.

# function with return value
def add_numbers(number1, number2):
    sum = number1 + number2
    
    # return the sum
    return sum

Since this function returns a value, we need to call this function by assigning the function call to a variable, so that the returned value is stored somewhere.

# function with return value
def add_numbers(number1, number2):
    sum = number1 + number2
    
    # return the sum
    return sum

# function call to store returned values
sum1 = add_numbers(12, 8)
sum2 = add_numbers(47, 38)    

print(sum1)    # Output: 20
print(sum2)    # Output: 85

Return multiple values

# function with return value
def add_subtract(number1, number2):
    sum = number1 + number2
    diff = number1 - number2
    return sum, diff

# function call to store returned values
sum, diff = add_subtract(12, 8)

print(sum)     # Output: 20
print(diff)    # Output: 4

Here, we are using the concept of multiple assignment, sum, diff = add_subtract(12, 8), to store both the returned values, return sum, diff.


Function Arguments

1. Positional Arguments

Positional arguments are assigned to the function's parameters based on their position in the function call.

# function definition
def display_info(name, age):
    print('Name:', name)
    print('Age:', age)
    
# function call
display_info('Maria', '26')

# Output:
# Name: Maria
# Age: 26

2. Keyword Arguments

Keyword arguments are assigned to the function's parameters by specifying the parameter names in the function call.

# function definition
def display_info(name, age):
    print('Name:', name)
    print('Age:', age)
    
# function call in correct order
display_info(name='Maria', age='26')
# Output:
# Name: Maria
# Age: 26

# function call with different order
display_info(age=32, name='Smith')
# Output:
# Name: Smith
# Age: 32

3. Default Arguments

We can define default values to parameters during the function definition.

def display_info(name, age=18):
    print('Name:', name)
    print('Age:', age)

The default value is used if we do not pass any values for the parameter during the function call.

# function definition
def display_info(name, age=18):
    print('Name:', name)
    print('Age:', age)

# function call with no age value
display_info('Smith')
# Output: 
# Name: Smith
# Age:

# function call with both values
display_info('Maria', '26')
# Output:
# Name: Maria
# Age: 26

4. args

args allows us to pass a variable number of positional arguments to a function.

# function definition that accepts variable parameters
def display_info(*args):
    
    # print all arguments
    for info in args:
        print(info)

# function call with 2 arguments
display_info('Smith', 32)
# Output:
# Smith
# 32

# function call with 3 arguments
display_info('Maria', 26, 'United States')
# Output:
# Maria
# 26
# United States

5. kwargs

kwargs allows us to pass a variable number of keyword arguments to a function.

# function definition
def display_info(**kwargs):
    
    # print all arguments
    for keyword, info in kwargs.items():
        print(keyword, ':', info)

# function call with 2 arguments
display_info(name='Smith', age=32)
# Output:
# name : Smith
# age : 32

# function call with 3 arguments
display_info(name='Maria', age=26, location='United States')
# Output:
# name : Maria
# age : 26
# location : United States

Variable Scope

Variables defined inside a function are not accessible outside of it. They are called local variables and will have local scope.

# function definition
def add_numbers(number1, number2):
    # local variable
    result = number1 + number2
    
# function call
add_numbers(12, 8)

# try to access local variable
print(result)

# Error: 'result' is not defined

Python List

Lists in Python allow us to work with multiple data at once.

Create a List

A list is created by placing items (elements) inside square brackets [], separated by commas.

numbers = [2, 3, 5, 7, 11]

Example: List

# empty list
empty_list = []
print(empty_list)   # Output: []

# list of integers
numbers = [1, 2, 3]
print(numbers)   # Output: [1, 2, 3]

# list of strings
names = ['Smith', 'Maria', 'Joseph']
print(names)    # Output: ['Smith', 'Maria', 'Joseph']

# list with mixed data types
mixed_list = [1, "Hello", 3.4]
print(mixed_list)   # Output: [1, 'Hello', 3.4]

# list with duplicate items
duplicate_list = [1, 2, 3, 1, 3]
print(duplicate_list)   # Output: [1, 2, 3, 1, 3]

Access List Items

1. Indexing

To access individual items from this list, we use an index, and it starts from 0. So, the index of the first item is 0, the index of the second item is 1, and so on.

names = ['Smith', 'Maria', 'Joseph']

# access first element
print(names[0])    # Output: Smith

# access the second element
print(names[1])    # Output: Maria

# access the third element
print(names[2])    # Output: Joseph

2. Negative Indexing

You can also use negative indexing to access list elements from the end.

The index of the last item is -1, the index of the second-last item is -2, and so on.

names = ['Smith', 'Maria', 'Joseph']

# access the last element
print(names[-1])    # Output: Joseph

# access the second element from last
print(names[-2])    # Output: Maria

# access the third element from  last
print(names[-3])    # Output: Smith

List Slicing

We can extract a sublist from a list using slicing.

Syntax:

slice = list[start:stop:step]

Here,

  • start - is the start index of the list from where slicing begins
  • stop - is the last index of the list up to which slicing ends
  • step - is the step size between start and stop

Example: With only the stop parameter

numbers = [2, 4, 6, 8, 10]

# access the first 3 elements of the list
sliced_numbers = numbers[:3]
print(sliced_numbers)

# Output: [2, 4, 6]

Here, when there is no start parameter, the slicing starts from index 0. So, numbers[:3] selects elements at indices 0, 1, and 2 (stop index is excluded).

Example: With only the start parameter

numbers = [2, 4, 6, 8, 10]

# access elements from index 3 up to the last
sliced_numbers = numbers[3:]
print(sliced_numbers)

# Output: [8, 10]

When there is no stop parameter, the slicing goes up to the last element. So, numbers[3:] selects elements at indices 3 and 4 (last element included).

Example: With both start and stop parameters

numbers = [2, 4, 6, 8, 10]

# access elements from index 2 up to 4
sliced_numbers = numbers[2:4]
print(sliced_numbers)

# Output: [6, 8]

Here, numbers[2:4] sliced the elements from index 2 up to the index B (not including the element at index 4).

Example: With the step parameter

We can also include the step parameter in a slice to specify the step size between elements.

numbers = [2, 4, 6, 8, 10, 12]

# access every other element of the list
sliced_numbers = numbers[0:5:2]
print(sliced_numbers)

# Output: [2, 6, 10]

Here, we have used 2 as the step parameter, so the sliced list includes every other element of the list.

Negative Slicing

We can also use negative indices during slicing to slice the list from the end.

numbers = [2, 4, 6, 8, 10, 12]

# access the last 3 elements
# missing stop and step parameters
print(numbers[-3:])      # Output: [8, 10, 12]

# access elements from index -5 to -2
# missing the step parameter
print(numbers[-5:-2])    # Output: [4, 6, 8]

# access every other element of the array from the end
# missing the stop parameter
print(numbers[-1::-2])   # Output: [12, 8, 4]

Reverse a List

Negative slicing provides an easier way to reverse a list.

numbers = [2, 4, 6, 8, 10, 12]

# reverse the list
print(numbers[::-1])

# Output: [12, 10, 8, 6, 4, 2]

List Operations

1. Change items

We can change list items by assigning a new value to that particular index.

languages = ['Python', 'Java', 'JavaScript', 'HTML']

# change the second item to 'C++'
languages[1] = 'C++'
print(languages)
# Output: ['Python', 'C++', 'JavaScript', 'HTML']

# change the last item to 'PHP'
languages[-1] = 'PHP'
print(languages)
# Output: ['Python', 'C++', 'JavaScript', 'PHP']

2. Delete Items

We can use the del keyword to delete items from a list.

languages = ['Python', 'Java', 'JavaScript', 'HTML']

# delete the second item
del languages[2]
print(languages)
# Output: ['Python', 'Java', 'HTML']

# delete the last item
del languages[-1]
print(languages)
# Output: ['Python', 'Java']

3. Loop through List

We can use a for loop to iterate through each item of a list.

languages = ['Python', 'Java', 'JavaScript', 'HTML']

for language in languages:
    print(language)

# Output:
# Python
# Java
# JavaScript
# HTML

List Methods

Python provides various built-in methods that can be used to perform different operations on a list.

1. Find length of a list

numbers = [2, 4, 6, 8, 10, 12]

# The len() function returns the
# number of elements in a list
print(len(numbers))    # Output: 6

2. Add Element to List

numbers = [2, 4, 6, 8, 10, 12]

# append() - adds element at the end of a list
numbers.append(14)
print(numbers)    # Output: [2, 4, 6, 8, 10, 12, 14]

# insert() - adds element at the specified index
numbers.insert(3, 22)
print(numbers)    # Output: [2, 4, 6, 22, 8, 10, 12, 14]

3. Remove Elements from List

languages = ['Python', 'Java', 'JavaScript', 'HTML']

# remove() - removes the specified element
languages.remove('HTML')
print(languages)
# Output: ['Python', 'Java', 'JavaScript']

# pop() - removes the element at the specified index
languages.pop(1)
print(languages)
# Output: ['Python', 'JavaScript']

# clear() - removes all items from the list
languages.clear()
print(languages)
# Output: []

4. Sort a List

numbers = [4, 8, 9, 2, 5, 3]

# sort() - sorts elements in the ascending order
numbers.sort()
print(numbers)
# Output: [2, 3, 4, 5, 8, 9]

languages = ['Python', 'C', 'HTML', 'Java']

# sort() - sorts elements in the alphabetical order
languages.sort()
print(languages)
# Output: ['C', 'HTML', 'Java', 'Python']

5. Reverse a List

numbers = [2, 3, 5, 7]

# reverse() - reverses elements of a list
numbers.reverse()
print(numbers)
# Output: [7, 5, 3, 2]

languages = ['Python', 'C', 'HTML', 'Java']

languages.reverse()
print(languages)
# Output: ['Java', 'HTML', 'C', 'Python']

6. Copy a List

prime_numbers = [2, 3, 5, 7]

# copy() - creates a shallow copy of the list
numbers = prime_numbers.copy()
print(numbers)
# Output: [2, 3, 5, 7]

Python String

1. Create a string

A string is a sequence of characters enclosed inside quotation marks (either single or double quotes)

# a string with single quotes
name = 'Johnny Smith'
print(name)       # Output: Johnny Smith

# a string with double quotes
address = "New York"
print(address)    # Output: New York

2. Access characters from a string

name = 'Johny Smith'

# access the character at index 3
print(name[3])    # Output: n

# access the last character
print(name[-1])   # Output: h

3. Escape Sequences

We can use the \ (backslash) operator to include special characters in strings.

# \" includes " in the string
text = 'I love \"Python\" programming.'
print(text)
# Output: I love "Python" programming.

# \n includes a new line in the string
text = 'Python is fun.\nI love this language.'
print(text)
# Output:
# Python is fun.
# I love this language.

String Operations

1. String concatenation

We can use the + operator to join (concatenate) two or more strings together.

first_name = 'Maria'
last_name = 'Roger'

# concatenate two strings
full_name = first_name + last_name
print(full_name)    # Output: MariaRoger

# concatenate three strings
full_name = first_name + ' ' + last_name
print(full_name)    # Output: Maria Roger

2. Slicing

We can also use slicing with a string to extract substrings.

movie = 'Avengers: Endgame'

# slice a substring from the first up to index 6
print(movie[:6])    # Output: Avenge

# slice a substring from the index 13 to last
print(movie[13:])    # Output: game

# slice a substring from index 10 up to 13
print(movie[10:13])    # Output: End

3. Reverse the string

We can use slicing with the negative indexing to reverse a string.

movie = 'Avengers: Endgame'

# reverse the string using slicing
print(movie[::-1])

# Output: emagdnE :sregnevA

4. String repetition

We can use the * operator to repeat a string multiple times.

movie = 'Avengers'

# repeat 'Avengers' 3 times
print(movie * 3)

# Output: AvengersAvengersAvengers

5. Compare Strings

movie1 = 'Avengers'
movie2 = 'Endgame'
movie3 = 'Avengers'

print(movie1 == movie2)
# Output: False

print(movie1 == movie3)
# Output: True

String Methods

Python provides various built-in methods to perform different operations on strings.

1. Change case of a string

movie = 'AVENGERS'

# lower() - converts the string to lowercase
lower_movie = movie.lower()
print(lower_movie)    # Output: avengers

# upper() - converts the string to uppercase
print(lower_movie.upper())    # Output: AVENGERS

2. Replace a substring

text = 'bat ball'

# replace() - replaces matching substring
replaced_text = text.replace('ba', 'ca')
print(replaced_text)

# Output: cat call

3. Find the index of a substring

text = 'Python is a fun language.'

# find() - finds the index of first occurrence
# of the specified substring
print(text.find('fun'))    # Output: 12

print(text.find('is'))    # Output: 7

4. Count the number of occurrence of a character

text = 'cat catch call carry'

# count() - counts the number of occurrence of a substring
print(text.count('ca')) 
# Output: 4

5. Split a string

text = 'Python is a fun language'

# split() - breaks a string with the specified separator
# returns a list of strings
print(text.split(' '))

# Output: ['Python', 'is', 'a', 'fun', 'language']

6. Join strings

list = ['Python', 'is', 'a', 'fun', 'language']

# join() - creates a string by joining all elements of iterable
# joins elements with ' ' (space)
text = ' '.join(list)
print(text)
# Output: Python is a fun language

# joins elements with '-' (dash)
text = '-'.join(list)
print(text)
# Output: Python-is-a-fun-language

7. Format a string

# format() - inserts values into a string
# format with default arguments
text = 'Her name is {} and she is {} years old.'.format('Maria', 26)
print(text)
# Output: Her name is Maria and she is 26 years old.

# format with positional argument
text = 'Her name is {0} and she is {1} years old.'.format('Maria', 26)
print(text)
# Output: Her name is Maria and she is 26 years old.

# format with keyword arguments
text = 'Her name is {name} and she is {age} years old.'.format(name='Maria', age=26)
print(text)
# Output: Her name is Maria and she is 26 years old.

f-string

We can also use f-strings to format a string in Python.

name = 'Maria'
age = 26

# f-string inserts values inside a string
text = f'Her name is {name} and she is {age} years old.'
print(text)

# Output: Her name is Maria and she is 26 years old.

Python Tuple

Similar to a list, a tuple is also an ordered collection of items. However, tuples are immutable - meaning we cannot change items of a tuple.

Create a Tuple

A tuple is created by placing items (elements) inside brackets (), separated by commas.

numbers = (2, 3, 5, 7)

Example: Tuple

# empty tuple
empty_tuple = ()
print(empty_tuple)   # Output: ()

# tuple of numbers
numbers = (2, 3, 5, 7)
print(numbers)   # Output: (2, 3, 5, 7)

# tuple of strings
names = ('Smith', 'Maria', 'Joseph')
print(names)    # Output: ('Smith', 'Maria', 'Joseph')

# tuple with mixed data types
mixed_list = (1, "Hello", 3.4)
print(mixed_list)   # Output: (1, 'Hello', 3.4)

# tuple with duplicate items
duplicate_list = (1, 2, 3, 1, 3)
print(duplicate_list)   # Output: (1, 2, 3, 1, 3)

Example: Tuple with only one element

If we create a tuple with a single element, it will be created as a string.

# tuple with a single item
text = ('Hello')
print(text)
print(type(text))

# Output: 
# Hello
# <class 'str'>

To create a tuple with only one item, we should include a trailing comma.

# tuple with a single item
text = ('Hello',)
print(text)
print(type(text))

# Output: 
# Hello
# <class 'tuple'>

Access Tuple Items

1. Indexing

To access individual items from a tuple, we use an index, and it starts from 0. So, the index of the first item is 0, the index of the second item is 1, and so on.

names = ('Smith', 'Maria', 'Joseph')

# access first element
print(names[0])    # Output: Smith

# access the second element
print(names[1])    # Output: Maria

# access the third element
print(names[2])    # Output: Joseph

2. Negative Indexing

You can also use negative indexing to access tuple elements from the end.

The index of the last item is -1, the index of the second-last item is -2, and so on.

names = ('Smith', 'Maria', 'Joseph')

# access the last element
print(names[-1])    # Output: Joseph

# access the second element from last
print(names[-2])    # Output: Maria

# access the third element from  last
print(names[-3])    # Output: Smith

Tuple Slicing

We can also use slicing with a tuple to extract a range of items from a tuple.

Syntax:

slice = tuple[start:stop:step]

Here,

  • start - is the start index of the tuple from where slicing begins
  • stop - is the last index of the tuple up to which slicing ends
  • step - is the step size between start and stop

Example: With only the stop parameter

numbers = (2, 4, 6, 8, 10)

# access the first 3 elements of the list
sliced_numbers = numbers[:3]
print(sliced_numbers)

# Output: (2, 4, 6)

Here, when there is no start parameter, the slicing starts from index 0. So, numbers[:3] selects elements at indices 0, 1, and 2 (stop index is excluded).

Example: With only the start parameter

numbers = (2, 4, 6, 8, 10)

# access elements from index 3 up to the last
sliced_numbers = numbers[3:]
print(sliced_numbers)

# Output: (8, 10)

When there is no stop parameter, the slicing goes up to the last element. So, numbers[3:] selects elements at indices 3 and 4 (last element included).

Example: With both start and stop parameters

numbers = (2, 4, 6, 8, 10)

# access elements from index 2 up to 4
sliced_numbers = numbers[2:4]
print(sliced_numbers)

# Output: (6, 8)

Here, numbers[2:4] sliced the elements from index 2 up to the index B (not including the element at index 4).

Example: With the step parameter

We can also include the step parameter in a slice to specify the step size between elements.

numbers = (2, 4, 6, 8, 10, 12)

# access every other element of the tuple
sliced_numbers = numbers[0:5:2]
print(sliced_numbers)

# Output: (2, 6, 10)

Here, we have used 2 as the step parameter, so the sliced tuple includes every other element of the tuple.

Negative Slicing

We can also use negative indices during slicing to slice the tuple from the end.

numbers = (2, 4, 6, 8, 10, 12)

# access the last 3 elements
# missing stop and step parameters
print(numbers[-3:])      # Output: (8, 10, 12)

# access elements from index -5 to -2
# missing the step parameter
print(numbers[-5:-2])    # Output: (4, 6, 8)

# access every other element of the tuple from the end
# missing the stop parameter
print(numbers[-1::-2])   # Output: (12, 8, 4)

Reverse a Tuple

Negative slicing provides an easier way to reverse a tuple.

numbers = (2, 4, 6, 8, 10, 12)

# reverse the tuple
print(numbers[::-1])

# Output: (12, 10, 8, 6, 4, 2)

Tuple Operations

1. Change tuple elements

Once we create a tuple, we cannot modify its items.

numbers = (2, 4, 6, 8, 10, 12)

# modify an element at an index 2
numbers[2] = 13
print(numbers)

# Error: 'tuple' object does not support item assignment

2. Loop through a tuple

We can iterate through items of a tuple using the for loop.

languages = ('Python', 'Java', 'JavaScript')

# loop through the tuple
for language in languages:
    print(language)
    
# Output:
# Python
# Java
# JavaScript

3. Delete tuple

It's possible to delete the tuple using the del keyword.

languages = ('Python', 'Java', 'JavaScript')

# delete languages
del languages

# languages is now deleted
print(languages)

# Error: languages is not defined

4. Tuple Concatenation

We can concatenate two or more tuples using the + operator.

first_tuple = (1, 3, 5, 7)
second_tuple = (2, 4, 6, 8)

# concatenate two tuples using the + operator
result = first_tuple + second_tuple
print(result)

# Output: (1, 3, 5, 7, 2, 4, 6, 8)

5. Tuple Repetition

We can repeat a tuple multiple times using the * operator.

numbers = (1, 3, 5)

# repeat the tuple 3 times
print(numbers * 3)

# Output: (1, 3, 5, 1, 3, 5, 1, 3, 5)

Tuple Methods

Python provides various built-in methods that can be used to perform different operations on a tuple.

1. Find the length of a tuple

languages = ('Python', 'Java', 'JavaScript')

# len() - returns the number of elements in a tuple
print(len(languages))    # Output: 3

2. Find the minimum and maximum element

numbers = (4, 8, 9, 2, 3)

# min() - returns the smallest element in a tuple
print(min(numbers))    # Output: 2

# max() - returns the largest element in a tuple
print(max(numbers))    # Output: 9

3. Count the number of occurrences of an element

numbers = (2, 4, 2, 4, 3, 2, )

# count() - returns the number of occurrences of an element
print(numbers.count(4))    # Output: 2
print(numbers.count(2))    # Output: 3

4. Created a tuple from other iterables

# create a list
languages_list = ['Python', 'Java', 'JavaScript']

# tuple() - creates a tuple from an iterable
languages = tuple(languages_list)
print(languages)

# Output: ('Python', 'Java', 'JavaScript')

5. Sort a tuple

languages = ('Python', 'C', 'Java')

# sorted() - returns a sorted list from elements of the tuple
languages_list = sorted(languages)
print(languages_list)
# Output: ['C', 'Java', 'Python']

# convert the sorted list to tuple
sorted_languages = tuple(languages_list)
print(sorted_languages)
# Output: ('C', 'Java', 'Python')

Python Dictionary

Similar to a list and tuple, a dictionary is a collection of items; however, each item of a dictionary is a key/value pair.

Create Dictionary

We can create a dictionary by placing a comma separated sequence of key: value pairs inside curly braces {}.

# empty dictionary
person = {}
print(person)
# Output: {}

# dictionary with two elements
person = {'name': 'Maria', 'age': 26}
print(person)
# Output: {'name': 'Maria', 'age': 26}

Key/Values

The keys of a dictionary must be unique and immutable (that cannot be changed); however, values can be duplicate and mutable.

# dictionary with unique keys
person = {'name': 'Maria', 'age': 26}
print(person)
# Output: {'name': 'Maria', 'age': 26}

# dictionary with duplicate keys
# Invalid dictionary
students = {'name': 'Maria', 'name': 'Johnny'}
print(students)
# Output: {'name': 'Johnny'}

# dictionary with duplicate values
person = {'name': 'Maria', 'age': 26, 'id': 26}
print(person)
# Output: {'name': 'Maria', 'age': 26, 'id': 26}

Dictionary Operations

1. Access Dictionary Values

We can access the value of a dictionary element by using its key in square brackets [].

person = {'name': 'Maria', 'age': 26}

# access the name
print(person['name'])    # Output: Maria

# access the age
print(person['age'])     # Output: 26

2. Update Dictionary Values

We can update the value of an existing element by assigning a new value to the corresponding key.

person = {'name': 'Maria', 'age': 26}

# change name to John and age to 32
person['name'] = 'John'
person['age'] = 32

print(person)

# Output: {'name': 'John', 'age': 32}

3. Add New Elements

We can also add a new key/value pair to a dictionary.

person = {'name': 'Maria', 'age': 26}

# add a new element
person['location'] = 'New York'
print(person)

# Output: {'name': 'Maria', 'age': 26, 'location': 'New York'}

4. Delete an Element

We can use the del keyword to delete an element from the dictionary.

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}
print(person)
# Output: {'name': 'Maria', 'age': 26, 'location': 'New York'}

# delete the element with key 'location'
del person['location']
print(person)
# Output: {'name': 'Maria', 'age': 26}

Dictionary Methods

Python provides various built-in methods that can be used to perform different operations on a dictionary.

1. Find the length of a dictionary

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# len() - returns the length of a dictionary
print(len(person))    # Output: 3

2. Find all elements of dictionary

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# key() - returns a list of all the keys in the dictionary
print(person.keys())
# Output: dict_keys(['name', 'age', 'location'])

# values() - returns a list of all the values
print(person.values())
# Output:dict_values(['Maria', 26, 'New York'])

# items() - returns a list of all key/value pairs
print(person.items())
# Output: dict_items([('name', 'Maria'), ('age', 26), ('location', 'New York')])

3. Remove Elements

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# pop() - removes the specified key/value pair
person.pop('location')
print(person)
# Output: {'name': 'Maria', 'age': 26}

# clear() - removes all elements
person.clear()
print(person)
# Output: {}

4. Copy Dictionary

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# copy() - returns a shallow copy of the dictionary
person_info = person.copy()
print(person_info)

# Output: {'name': 'Maria', 'age': 26, 'location': 'New York'}

5. Get Dictionary Values

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# get() - returns the value of the specified key
print(person.get('name'))    # Output: Maria
print(person.get('age'))     # Output: 26

6. Iterate through Dictionary

person = {'name': 'Maria', 'age': 26, 'location': 'New York'}

# iterate through keys and values using methods
for key in person.keys():
    print(key, ':', person[key])

# iterate through keys and values without methods
for key in person:
    print(key, ':', person[key])

Python Sets

There are 3 things that make sets different from lists and tuples in Python:

  • elements of a set are not in any particular order
  • a set cannot contain duplicate items

Create a Set

# set of strings
animals = {'dog', 'cat', 'tiger'}
print(animals)
# Output: {'dog', 'cat', 'tiger'}

# set of mixed data types
mixed_set = {'Maria', 26, 167.32}
print(mixed_set)
# Output: {26, 'Maria', 167.32}

# duplicate elements in a set
numbers = {1, 2, 3, 5, 2}
print(numbers)
# Output: {1, 2, 3, 5}

Create set using Set()

# set() is a constructor that can be used to create a set
animals = set({'dog', 'cat', 'horse'})
print(animals)

# Output: {'cat', 'horse', 'dog'}

Empty Set

If we create an empty set using {}, it will be a dictionary. Hence, we use set().

# empty set using {}
set1 = {}
print(set1)    # Output: {}
print(type(set1))    # Output: <class 'dict'>

# empty set using set()
set2 = set()
print(set2)    # Output: set()
print(type(set2))    # Output: <class 'set'>

Set Methods

Python provides various built-in methods that can be used to perform different operations on a set.

1. Find the length of a set

languages = {'Python', 'Java', 'C', 'C++'}

# len() - returns the length of a set
print(len(languages))    # Output: 4

2. Add elements to a set

languages = {'Python', 'Java', 'C'}

# add() - inserts the specified element to a set
languages.add('C++')
print(languages)
# Output: {'Java', 'Python', 'C', 'C++'}

3. Remove Elements from a set

languages = {'Python', 'Java', 'C', 'C++'}

# remove() - removes the specified element
languages.remove('C')
print(languages)
# Output: {'Python', 'Java'}

# pop() - removes a random element from the set
languages.pop()
print(languages)
# Output: {'Java', 'Python'}

# clear() - removes entire elements of the set
languages.clear()
print(languages)
# Output: set()

4. Copy a set

languages = {'Python', 'Java', 'C'}

# copy() - returns a shallow copy of a set
programming_languages = languages.copy()
print(programming_languages)

# Output: {'Java', 'C', 'Python'}

5. Create a set from other iterables

languages = {'Python', 'Java'}
list_languages = ['C++', 'PHP']

# update() - adds multiple elements from an iterable to a set
languages.update(list_languages)
print(languages)

# Output: {'C++', 'Python', 'Java', 'PHP'}

6. Loop through a set

languages = {'Python', 'Java', 'C', 'C++'}

for language in languages:
    print(language)
    
# Output:
# Python
# C
# C++
# Java

Set Operations

1. Union of two sets

numbers1 = {1, 2, 3, 4, 5, 6}
numbers2 = {2, 4, 6, 8, 10}

# union of two sets using |
print(numbers1 | numbers2)
# Output: {1, 2, 3, 4, 5, 6, 8, 10}

# union() - returns the union of two sets
print(numbers1.union(numbers2))
# Output: {1, 2, 3, 4, 5, 6, 8, 10}

2. Intersection of two sets

numbers1 = {1, 2, 3, 4, 5, 6}
numbers2 = {2, 4, 6, 8, 10}

# intersection of two sets using &
print(numbers1 & numbers2)
# Output: {2, 4, 6}

# intersection() - returns the intersection of two sets
print(numbers1.intersection(numbers2))
# Output: {2, 4, 6}

3. Difference of two sets

numbers1 = {1, 2, 3, 4, 5, 6}
numbers2 = {2, 4, 6, 8, 10}

# difference of two sets
print(numbers1 - numbers2)
# Output: {1, 3, 5}

# difference() - returns the difference of two sets
print(numbers1.difference(numbers2))
# Output: {1, 3, 5}

4. Subset and superset

numbers1 = {1, 2, 3, 4, 5, 6}
numbers2 = {2, 4, 6}
numbers3 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

# <= checks if a set is subset of another set
print(numbers2 <= numbers1)    # Output: True

# issubset() - checks if a set is the subset of another
print(numbers2.issubset(numbers1))    # Output: True

# >= checks if a set is superset of another set
print(numbers3 >= numbers1)    # Output: True

# issuperset() - checks if a set is the superset of another
print(numbers3.issuperset(numbers1))    # Output: True