0% found this document useful (0 votes)
54 views211 pages

Java Python Tutorial

This document is a comprehensive tutorial on Python, covering its features, applications, and various programming concepts such as data structures, object-oriented programming, exception handling, and file handling. It emphasizes Python's simplicity, versatility, and extensive library support, making it suitable for web development, data science, and machine learning. Additionally, it includes practical examples, quizzes, and resources for further learning.

Uploaded by

Amanuel Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views211 pages

Java Python Tutorial

This document is a comprehensive tutorial on Python, covering its features, applications, and various programming concepts such as data structures, object-oriented programming, exception handling, and file handling. It emphasizes Python's simplicity, versatility, and extensive library support, making it suitable for web development, data science, and machine learning. Additionally, it includes practical examples, quizzes, and resources for further learning.

Uploaded by

Amanuel Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 211

Python Tutorial - Learn Python

Programming Language


Python is one of the most popular programming languages. It’s simple to use, packed
with features and supported by a wide range of libraries and frameworks. Its clean
syntax makes it beginner-friendly. It's
 A high-level language, used in web development, data science, automation, AI and
more.
 Known for its readability, which means code is easier to write, understand and
maintain.
 Backed by library support, so we don’t have to build everything from scratch,
there’s probably a library that already does what we need.

Why to Learn Python?


 Requires fewer lines of code compared to other programming languages.
 Provides Libraries / Frameworks like Django, Flask, Pandas, Tensorflow, Scikit-
learn and many more for Web Development, AI/ML, Data Science and Data
Analysis
 Cross-platform, works on Windows, Mac and Linux without major changes.
 Used by top tech companies like Google, Netflix and NASA.
 Many Python coding job opportunities in Software Development, Data Science and
AI/ML.
Do you wish to learn Python in a scheduled manner ? Try our ongoing free course
Python Skillup with weekly topic coverage, notes, daily quizzes and coding problems.

First Python Program


Here is a simple Python code, printing a string. We recommend you to edit the code
and try to print your own name.

Print ("Hello World")

Output

Hello World

1. Python Basics
1|Page
In this section, we’ll cover the basics of Python programming, including installing
Python, writing first program, understanding comments and working with variables,
keywords and operators. These are essential building blocks to get started with
Python coding.
Before starting to learn python we need to install python on our system.
 Introduction
 Input and Output
 Variables
 Operators
 Quiz: Basics, I/O
 Keywords
 Data Types
 Quiz: Data Types, Numbers, Boolean
 Conditional Statements
 Python Loops
 Quiz: Control Flow, Loops
2. Python Functions
Python Functions are the backbone of organized and efficient code in Python. Here, in
this section of Python 3 tutorial we'll explore their syntax, parameter handling, return
values and variable scope. From basic concepts to advanced techniques like closures
and decorators. Along the way, we'll also introduce versatile functions like range(),
map, filter and lambda functions.
 Python Functions
 Pass Statement in Function
 Global and Local Variables
 Recursion in Python
 *args and **kwargs in Function
 ‘Self’ as Default Argument
 First Class Function
 Lambda Function
 Map, Reduce and Filter Function
 Inner Function
 Decorators
 Quiz: Functions

3. Python Data Structures


Python offers versatile collections of data types, including lists, string, tuples, sets,
dictionaries and arrays. In this section, we will learn about each data types in detail.
 Strings
 List
 Quiz: List, String
 Tuples
 Dictionary
 Quiz: Tuples, Dictionary
 Sets

2|Page
 Arrays
 List Comprehension
 Quiz: Sets, Arrays, List Comprehension
Python's collections module offers essential data structures, including the following:
 Counters
 Heapq
 Deque
 OrderedDict
 Defaultdict
 Quiz: Counters, Heapq, Deque, OrderedDict
To learn data structure and algorithm with python in detail, you can refer to our DSA
with Python Tutorial.

4. Python OOPs Concepts


In this section of Python OOPs, we'll explore the core principles of object-oriented
programming (OOP) in Python. From encapsulation to inheritance, polymorphism,
abstract classes and iterators, we'll cover the essential concepts that helps you to
build modular, reusable and scalable code.
 Python OOPs
 Classes and Objects
 Polymorphism
 Inheritance
 Abstract
 Encapsulation
 Iterators
 Quiz: OOPs

5. Python Exception Handling


In this section of Python Tutorial, we'll explore Python Exception Handling that how
Python deals with unexpected errors, enabling us to write fault-tolerant code. We'll
cover file handling, including reading from and writing to files.
 Python Exception Handling
 Built-in Exception
 User defined Exception
 Quiz: Exception Handling

6. File Handling
In this section, we will cover file handling, including reading from and writing to files.
 File Handling
 Read Files
 Write/Create Files
 OS Module
 pathlib Module
 Directory Management
 Quiz: File Handling

7. Python Database Handling


3|Page
In this section we will learn how to access and work with MySQL and MongoDB
databases
 Python MongoDB Tutorial
 Python MySQL Tutorial

8. Python Packages or Libraries


Python is a huge collection of Python Packages standard libraries that make
development easier. These libraries help with a wide range of tasks and can save you
a lot of time by providing ready-to-use tools.
Some commonly used types of libraries in Python include:
 Python Packages
 Built-in Modules in Python
 Python DSA Libraries
 Python GUI Libraries

9. Data Science with Python


1. Foundational Libraries: These are the libraries that form the base for all data
science work. Start here to build a strong foundation.
 NumPy
 Pandas
 Matplotlib
2. Advanced Visualization and Statistical Tools: Once you’re comfortable with
basic data handling and visualization, move to creating cleaner visuals and performing
statistical analysis.
 Seaborn
 Statsmodel
3. Machine Learning Libraries: After data manipulation and visualization, learn
machine learning, starting with simpler models and moving to advanced ones.
 Scikit-learn
 XGBoost /LightGBM
4. Deep Learning Frameworks: If you’re interested in AI and deep learning, these
libraries will allow you to build and train neural networks.
 TensorFlow and Keras
 PyTorch
To learn more, you can refer to Python for Data Science.

10. Web Development with Python


1. Core Web Frameworks (Backend Development with Python): These are the
tools for building Python-based web applications.
 Flask
 Django
2. Database Integration: Learn how to connect Python web frameworks to databases
for storing and retrieving data.
 SQLite
 SQLAlchemy
 Django ORM

4|Page
3. Front-End and Backend Integration: Learn how to connect Python backends with
front-end technologies to create dynamic, full-stack web applications.
 Jinja2 (Flask)
 Django Templates
4. API Development: Learn to build APIs (Application Programming Interfaces) for
connecting your backend with front-end apps or other services.
 Flask-RESTful
 Django REST Framework (DRF)
To learn more, you can refer to Python for Web Development.

Python Quizzes
Python quiz page covers topics including variables, data types and how to manage
output effectively. You'll explore operators and control flow to structure our code, along
with loops (for and while) for repetitive tasks. Additionally, you'll gain knowledge with
Python data structures such as lists, tuples, dictionaries and sets.
 Quizzes
Python Practice
The Python Coding Practice Problems page offers exercises for all skill levels,
covering basics, loops, functions and OOP. You'll work with lists, strings, dictionaries,
sets and advanced structures like heaps and deques. These problems help build a
strong foundation and boost confidence in solving real-world coding challenges.
 Python Coding Problems
Features of Python
Python stands out because of its simplicity and versatility, making it a top choice for
both beginners and professionals. Here are some key features or characteristics:
1. Easy to Read and Write: Python’s syntax is clean and simple, making the code
easy to understand and write. It is suitable for beginners.
2. Interpreted Language: Python executes code line by line, which helps in easy
debugging and testing during development.
3. Object-Oriented and Functional: Python supports both object-oriented and
functional programming, giving developers flexibility in how they structure their
code.
4. Dynamically Typed: You don’t need to specify data types when declaring
variables; Python figures it out automatically.
5. Extensive Libraries: Python has a rich collection of libraries for tasks like web
development, data analysis, machine learning and more.
6. Cross-Platform: Python can run on different operating systems like Windows,
macOS and Linux without modification.
7. Community Support: Python has a large, active community that continuously
contributes resources, libraries and tools, making it easier to find help or solutions.
This Python tutorial is updated based on latest Python 3.13.1 version.

Applications of Python
 Web Development: Frameworks like Django and Flask can be used to create
dynamic websites and web applications quickly and efficiently.

5|Page
 Data Science & Analysis: Python is most preferred language for data analysis,
visualization and handling large datasets. Because of extensive libraries like
Pandas, NumPy and Matplotlib.
 Machine Learning & AI: Python is popular in AI and machine learning because of
its powerful libraries like TensorFlow, Keras and Scikit-learn.
 Scripting & Automation: Python’s simplicity makes it ideal for writing scripts that
automate tasks in different systems, from server management to file handling.
Python is commonly used to automate repetitive tasks, making processes faster
and more efficient.
 Web Scraping: Libraries like Beautiful Soup and Scrapy.
 Desktop App Development: Python can be used to build desktop applications
using frameworks like Tkinter and PyQt. Python is also used for game
development, with libraries like Pygame to create simple games.
Python vs. Other Programming Languages
Below is the comparison of Python with C, C++ and Java:

Definition for Each points

Python Introduction
Last Updated : 23 Jul, 2025



Python was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation. It was designed with focus on code readability and its
syntax allows us to express concepts in fewer lines of code.
Key Features of Python
 Python’s simple and readable syntax makes it beginner-friendly.
 Python runs seamlessly on Windows, macOS and Linux.
 Includes libraries for tasks like web development, data analysis and machine
learning.
 Variable types are determined automatically at runtime, simplifying code writing.
 Supports multiple programming paradigms, including object-oriented, functional
and procedural programming.
 Python is free to use, distribute and modify.
Understanding Hello World Program in Python
Hello, World! in python is the first python program which we learn when we start
learning any program. It’s a simple program that displays the message “Hello,
World!” on the screen.
Hello World Program
Here’s the “Hello World” program:
6|Page
# This is a comment. It will not be executed.

print("Hello, World!")

Output
Hello, World!
How does this work:
 print() is a built-in Python function that tells the computer to show something on
the screen.
 The message "Hello, World!" is a string, which means it's just text. In Python,
strings are always written inside quotes (either single ' or double ").
 Anything after # in a line is a comment. Python ignores comments when running
the code, but they help people understand what the code is doing.
 Comments are helpful for explaining code, making notes or skipping lines while
testing.
We can also write multi-line comments using triple quotes:

"""
This is a multi-line comment.
It can be used to describe larger sections of code.
"""
To understand comments in detail, refer to article: Comments.

Indentation in Python
In Python, Indentation is used to define blocks of code. It tells the Python interpreter
that a group of statements belongs to a specific block. All statements with the same
level of indentation are considered part of the same block. Indentation is achieved
using whitespace (spaces or tabs) at the beginning of each line. The most common
convention is to use 4 spaces or a tab, per level of indentation.
Example:

print("I have no indentation")

print("I have tab indentaion")


Output:
Hangup (SIGHUP)
File "/home/guest/sandbox/Solution.py", line 3
print("I have tab indentaion")
IndentationError: unexpected indent
Explanation:
 first print statement has no indentation, so it is correctly executed.
 second print statement has tab indentation, but it doesn't belong to a new block
of code. Python expects the indentation level to be consistent within the same
block. This inconsistency causes an IndentationError.
To understand Indentation in detail, refer to article: Indentation
7|Page
Famous Application Built using Python
 YouTube: World’s largest video-sharing platform uses Python for features like
video streaming and backend services.
 Instagram: This popular social media app relies on Python’s simplicity for scaling
and handling millions of users.
 Spotify: Python is used for backend services and machine learning to personalize
music recommendations.
 Dropbox: The file hosting service uses Python for both its desktop client and
server-side operations.
 Netflix: Python powers key components of Netflix’s recommendation engine and
content delivery systems (CDN).
 Google: Python is one of the key languages used in Google for web crawling,
testing and data analysis.
 Uber: Python helps Uber handle dynamic pricing and route optimization using
machine learning.
 Pinterest: Python is used to process and store huge amounts of image data
efficiently.
What can we do with Python?
Python is used for:
 Web Development: Frameworks like Django, Flask.
 Data Science and Analysis: Libraries like Pandas, NumPy, Matplotlib.
 Machine Learning and AI: TensorFlow, PyTorch, Scikit-learn.
 Automation and Scripting : Automate repetitive tasks.
 Game Development: Libraries like Pygame.
 Web Scraping: Tools like BeautifulSoup, Scrapy.
 Desktop Applications : GUI frameworks like Tkinter, PyQt.
 Scientific Computing : SciPy, SymPy.
 Internet of Things (IoT) : MicroPython, Raspberry Pi.
 DevOps and Cloud: Automation scripts and APIs.
 Cybersecurity: Penetration testing and ethical hacking tools.

Input and Output in Python


Last Updated : 28 Jul, 2025



Understanding input and output operations is fundamental to Python programming.


With the print() function, we can display output in various formats, while the input()
function enables interaction with users by gathering input during program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it returns the user
input in form of a string.
Example:

8|Page
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!
The code prompts the user to input their name, stores it in the variable "name" and
then prints a greeting message addressing the user by their entered name.
To learn more about taking input, please refer: Taking Input in Python

Printing Output using print() in Python


At its core, printing output in Python is straightforward, thanks to the print() function.
This function allows us to display text, variables and expressions on the console. Let's
begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double quotes. When
executed, this statement will output the text to the console.

print("Hello, World!")

Output
Hello, World!

Printing Variables
We can use the print() function to print single and multiple variables. We can print
multiple variables by separating them with commas. Example:

# Single variable
s = "Bob"
print(s)

# Multiple Variables
s = "Alice"
age = 25
city = "New York"
print(s, age, city)

Output
Bob
Alice 25 New York

Take Multiple Input in Python


We are taking multiple input from the user in a single line, splitting the values entered
by the user into separate variables for each value using the split() method. Then, it
prints the values with corresponding labels, either two or three, based on the number
of inputs provided by the user.
# taking two inputs at a time
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)

9|Page
print("Number of girls: ", y)

# taking three inputs at a time


x, y, z = input("Enter three values: ").split()
print("Total number of students: ", x)
print("Number of boys is : ", y)
print("Number of girls is : ", z)
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Enter three values: 5 10 15
Total number of students: 5
Number of boys is : 10
Number of girls is : 15

How to Change the Type of Input in Python


By default input() function helps in taking user input as string. If any user wants to take
input as int or float, we just need to typecast it.
Print Names in Python
The code prompts the user to input a string (the color of a rose), assigns it to the
variable color and then prints the inputted color.
# Taking input as string
color = input("What color is rose?: ")
print(color)
Output
What color is rose?: Red
Red
Print Numbers in Python
The code prompts the user to input an integer representing the number of roses,
converts the input to an integer using typecasting and then prints the integer value.
# Taking input as int
# Typecasting to int
n = int(input("How many roses?: "))
print(n)
Output
How many roses?: 88
Print Float/Decimal Number in Python
The code prompts the user to input the price of each rose as a floating-point number,
converts the input to a float using typecasting and then prints the price.
# Taking input as float
# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output
Price of each rose?: 50.3050.3

10 | P a g e
Find DataType of Input in Python
In the given example, we are printing the type of variable x. We will determine the type
of an object in Python.

a = "Hello World"
b = 10
c = 11.22
d = ("Geeks", "for", "Geeks")
e = ["Geeks", "for", "Geeks"]
f = {"Geeks": 1, "for":2, "Geeks":3}

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))

Output
<class 'str'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>
<class 'dict'>

Output Formatting
Output formatting in Python with various techniques including the format() method,
manipulation of the sep and end parameters, f-strings and the versatile % operator.
These methods enable precise control over how data is displayed, enhancing the
readability and effectiveness of your Python programs.
Example 1: Using Format()

amount = 150.75
print("Amount: ${:.2f}".format(amount))

Output
Amount: $150.75

Example 2: Using sep and end parameter

# end Parameter with '@'


print("Python", end='@')
print("GeeksforGeeks")

11 | P a g e
# Seprating with Comma
print('G', 'F', 'G', sep='')

# for formatting a date


print('09', '12', '2016', sep='-')

# another example
print('pratik', 'geeksforgeeks', sep='@')

Output
Python@GeeksforGeeks
GFG
09-12-2016
pratik@geeksforgeeks

Example 3: Using f-string

name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")

Output
Hello, My name is Tushar and I'm 23 years old.

Example 4: Using % Operator


We can use '%' operator. % values are replaced with zero or more value of elements.
The formatting using % is similar to that of ‘printf’ in the C programming language.
 %d –integer
 %f – float
 %s – string
 %x –hexadecimal
 %o – octal
# Taking input from the user
num = int(input("Enter a value: "))

add = num + 5

# Output
print("The sum is %d" %add)
Output
Enter a value: 50The sum is 55

Taking Conditional User Input in Python


In Python, taking conditional user input means getting input from the user and making
decisions based on that input. You usually use the input() function to get the value and
then use if-else statements to check conditions.
 input() is used to take user input as a string.

12 | P a g e
 You can use int() or float() to convert it if needed.
 Use if, elif, and else to apply conditions to the input.
Related Posts:
 input() function
 Taking input
 Taking multiple input
 Taking Conditional User Input
 How to take integer input
 Get a String as input from user
 Format()
 sep and end parameter
 f-string
 % Operator
 Take input from stdin in Python
 Difference between input() and raw_input() functions in Python
 Python Input Methods for Competitive Programming
Python Variables
Last Updated : 11 Jul, 2025



In Python, variables are used to store data that can be referenced and manipulated
during program execution. A variable is essentially a name that is assigned to a
value. Unlike many other programming languages, Python variables do not require
explicit declaration of type. The type of the variable is inferred based on the value
assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our
program.
Example:

# Variable 'x' stores the integer value 10


x=5

# Variable 'name' stores the string "Samantha"


name = "Samantha"

print(x)
print(name)

Output
5
Samantha

13 | P a g e
In this article, we’ll explore the concept of variables in Python, including their syntax,
characteristics and common operations.
Table of Content
 Rules for Naming Variables
 Assigning Values to Variables
 Multiple Assignments
 Type Casting a Variable
 Getting the Type of Variable
 Object Reference in Python
 Delete a Variable Using del Keyword
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores ( _).
 A variable name cannot start with a digit.
 Variable names are case-sensitive ( myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.
Valid Example:

age = 21
_colour = "lilac"
total_score = 90
Invalid Example:

1name = "Error" # Starts with a digit


class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment
Variables in Python are assigned values using the = operator.

x=5
y = 3.14
z = "Hi"
Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold
different types of values during execution.

x = 10
x = "Now a string"
Multiple Assignments
14 | P a g e
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single line, which
can be useful for initializing variables with the same value.

a = b = c = 100
print(a, b, c)

Output
100 100 100

Assigning Different Values


We can assign different values to multiple variables simultaneously, making the code
concise and easier to read.

x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output
1 2.5 Python

Type Casting a Variable


Type casting refers to the process of converting the value of one data type into
another. Python provides several built-in functions to facilitate casting, including int(),
float() and str() among others.
Basic Casting Functions
 int() - Converts compatible values to an integer.
 float() - Transforms values into floating-point numbers.
 str() - Converts any data type into a string.
Examples of Casting:

# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string

# Display results
print(n)
print(f)

15 | P a g e
print(s2)

Output
10
5.0
25

Getting the Type of Variable


In Python, we can determine the type of a variable using the type() function. This
built-in function returns the type of the object passed to it.
Example Usage of type()

# Define variables with different data types


n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True

# Get and print the type of each variable


print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))

Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>

Object Reference in Python


Let us assign a variable x to value 5.
x=5

16 | P a g e
When x = 5 is executed, Python creates an object to represent the value 5 and
makes x reference this object.
Now, if we assign another variable y to the variable x.
y=x

Explanation:
 Python encounters the first statement, it creates an object for the value 5 and
makes x reference it. The second statement creates y and references the same
object as x, not x itself. This is called a Shared Reference, where multiple
variables reference the same object.
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and makes x reference this new
object.

17 | P a g e
Explanation:
 The variable y remains unchanged, still referencing the original object 5.
If we now assign a new value to y:
y = "Computer"

 Python creates yet another object for "Computer" and updates y to reference it.
 The original object 5 no longer has any references and becomes eligible for
garbage collection.
Key Takeaways:
 Python variables hold references to objects, not the actual objects themselves.
 Reassigning a variable does not affect other variables referencing the same
object unless explicitly updated.
Delete a Variable Using del Keyword
We can remove a variable from the namespace using the del keyword. This
effectively deletes the variable and frees up the memory it was using.
Example:

18 | P a g e
# Assigning value to variable
x = 10
print(x)

# Removing the variable using del


del x

# Trying to print x after deletion will raise an error


# print(x) # Uncommenting this line will raise NameError: name 'x' is not defined
Explanation:
 del x removes the variable x from memory.
 After deletion, trying to access the variable x results in a NameError, indicating
that the variable no longer exists.
Practical Examples
1. Swapping Two Variables
Using multiple assignments, we can swap the values of two variables without
needing a temporary variable.

a, b = 5, 10
a, b = b, a
print(a, b)

Output
10 5

2. Counting Characters in a String


Assign the results of multiple operations on a string to variables in one line.
word = "Python"
length = len(word)
print("Length of the word:", length)

Output
Length of the word: 6

Scope of a Variable
In Python, the scope of a variable defines where it can be accessed in the program.
There are two main types of scope: local and global.
Local Variables:
 Defined within a function or block, accessible only inside that scope.
 Destroyed once the function/block ends.
 Temporary, used for short-term data.
Global Variables:
 Defined outside functions, accessible throughout the program.
19 | P a g e
 To modify within a function, use the global keyword.
 Persist in memory for the program’s duration, useful for shared data.
To learn about it in detail, refer to local and global.
Python Quiz:
 Python Variable Quiz
Related Posts:
 Global and Local Variables in Python
 Scope of Variables
 int() in Python
 float() in Python
 str() in Python
 Assign function to a Variable in Python
 Insert a Variable into a String in Python
 Type Casting in Python
Recommended Problems:
 Type Conversion
 TypeCast And Double It
 Swap The Numbers
 Sum of N Numbers
 Int Str
Python Variables - Python
What is the scope of a variable in Python?
The scope of a variable determines where it can be accessed. Local variables are
scoped to the function in which they are defined, while global variables can be
accessed throughout the program.
Can we change the type of a variable after assigning it?
Yes, Python allows dynamic typing. A variable can hold a value of one type initially
and be reassigned a value of a different type later.
What happens if we use an undefined variable?
Using an undefined variable raises a NameError. Always initialize variables before
use.
How can we delete a variable in Python?
We can delete a variable in Python using the del keyword:
x = 10
del x
#print(x) # Raises a NameError since 'x' has been deleted
Python Operators
Last Updated : 19 Jun, 2025



20 | P a g e
In Python programming, Operators in general are used to perform operations on
values and variables. These are standard symbols used for logical and arithmetic
operations. In this article, we will look into different types of Python operators.
 OPERATORS: These are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.
Types of Operators in Python

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is
used.
Example of Arithmetic Operators in Python:
# Variables
a = 15
b=4

# Addition
print("Addition:", a + b)

# Subtraction
print("Subtraction:", a - b)

# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

# Exponentiation
print("Exponentiation:", a ** b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
21 | P a g e
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Note: Refer to Differences between / and // for some interesting facts about these two
Python operators.
Comparison of Python Operators
In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.
Example of Comparison Operators in Python
Let's see an example of Comparison Operators in Python.
a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True

Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Example of Logical Operators in Python:
a = True
b = False
print(a and b)
print(a or b)
print(not a)

22 | P a g e
Output
False
True
False

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are used
to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example of Bitwise Operators in Python:
a = 10
b=4

print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables. This operator
is used to assign the value of the right side of the expression to the left side operand.
Example of Assignment Operators in Python:
a = 10
b=a
print(b)
b += a

23 | P a g e
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two values
are located on the same part of the memory. Two variables that are equal do not imply
that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example of Identity Operators in Python:
a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True

Membership Operators in Python


In Python, in and not in are the membership operators that are used to test whether a
value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence
Examples of Membership Operators in Python:
x = 24
y = 20
list = [10, 20, 30, 40, 50]

24 | P a g e
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in
version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.
Syntax : [on_true] if [expression] else [on_false]
Examples of Ternary Operator in Python:
a, b = 10, 20
min = a if a < b else b

print(min)

Output
10

Precedence and Associativity of Operators in Python


In Python, Operator precedence and associativity determine the priorities of the
operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different precedence to
determine which operation to perform first.
Example:
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:

25 | P a g e
print("Good Bye!!")

Output
610
Hello! Welcome.

Operator Associativity in Python


If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from Right
to Left.
Example:
print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Output
100.0
6
0
512
To try your knowledge of Python Operators, you can take out the quiz on Operators in
Python.
Python Operator Exercise Questions
Below are two Exercise Questions on Python Operators. We have covered arithmetic
operators and comparison operators in these exercise questions. For more exercises
on Python Operators visit the page mentioned below.
Q1. Code to implement basic arithmetic operations on integers
num1 = 5
num2 = 2

sum = num1 + num2


difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
remainder = num1 % num2

print("Sum:", sum)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)

26 | P a g e
Output
Sum: 7
Difference: 3
Product: 10
Quotient: 2.5
Remainder: 1
Q2. Code to implement Comparison operations on integers
num1 = 30
num2 = 35

if num1 > num2:


print("The first number is greater.")
elif num1 < num2:
print("The second number is greater.")
else:
print("The numbers are equal.")

Output
The second number is greater.

Quiz:
 Python Operators Quiz
Related Posts:
 Arithmetic Operators
 Comparison Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Identity Operators and Membership Operators
 Modulo Operator
 Division Operator
 Ternary Operator
 Operator Overloading
 OR operator
 Why are there no ++ and - Operator in Python
 How to do Math in Python 3 with Operators
 Difference between == and is Operator in Python
Python Fundamentals
In this quiz we are going to practice questions to grasp python basics, variables, keywords and
python operators.
Question 1
27 | P a g e
Which of the following is a valid way to comment in Python?
 A
// This is a comment
 B
# This is a comment
 C
<!-- This is a comment -->
 D
/* This is a comment */
Discuss it
Question 2
What is the result of the following expression in Python: 5 + 2 * 3
 A
21
 B
17
 C
11
 D
1
Discuss it
Explanation

In Python, multiplication ( *) happens before addition (+) due to operator precedence.


Step-by-step:
1. Multiply first: 2 * 3 = 6
2. Add next: 5 + 6 = 11
Question 3
What will be the output of the following code snippet?
a = 5
b = 2
print(a // b)
 A
2.5

 B
2
 C
2.0
 D
2.00
Discuss it
Question 4
What is the output of the following code?
num1 = "5"
num2 = 3
result = num1 * num2
print(result)
 A

28 | P a g e
15

 B
"555"
 C
8
 D
"333"
Discuss it
Question 5
What is the output of the following code?
value = 2 + 3 * 4 / 2
print(value)
 A
4.5

 B
10.0
 C
8.0
 D
12.0
Discuss it
Question 6
What is the output of the following code?
x = "5"
y = "2"
print(x + y)
 A
7

 B
52
 C
10
 D
3
Discuss it
Question 7
Which of the following statements is true about Python variables?
 A
Variables must be declared before they are used.
 B
Variables can contain only letters.
 C
Python variables are case-sensitive.
 D
Python variables cannot be reassigned.
Discuss it
29 | P a g e
Question 8
Which of the following is the correct way to take user input in Python?
 A
input()

 B
get_input()
 C
user_input()
 D
read_input()
Discuss it
Question 9
Which of the following is the correct type conversion for converting a floating-point number to an
integer in Python?
 A
int(float_num)
 B
integer(float_num)
 C
float_to_int(float_num)
 D
convert_int(float_num)
Discuss it
Question 10
What is the value of result in the following code?
num = "8"
result = int(num) + 5
print(result)
 A
13

 B
"85"
 C
58
 D
"13"
Discuss it
Question 11
 Which of the following is the correct way to round a floating-point number to the nearest
integer in Python?
.A
round_up()
 B
ceil()
 C
round()
 D
floor()

30 | P a g e
Discuss it
Question 12
Which function overloads the >> operator?
 A
more()
 B
gt()
 C
ge()
 D
None of the above
Discuss it
Explanation

rshift() overloads the >> operator


Question 13
Find the output of the below python code:
str = "GFG"
print(not (not(str and "")))
 A
GFG
 B
Empty String
 C
True
 D
False
Discuss it
Explanation

The expression str and "" evaluates to "" (falsy), not("") becomes True, and not(True) results in
False.
Question 14
Find the output of the below python code:
print(oct(23)+oct(23))
 A
Error
 B
0o123123
 C
0o270o27
 D
0o27027
Discuss it
Explanation

31 | P a g e
oct() function returns the octal representation of an integer as a string prefixed with 0o. Since
string concatenation is used here (+ operator between two strings), the result of oct(23) +
oct(23) is the concatenation of '0o27' and '0o27', producing '0o270o27'.
Question 15
Find the output of the below python code:
print(~(~2))
 A
-3
 B
Error
 C
2
 D
None of the above
Discuss it
Explanation

Negation of negation is positive, hence correct answer is 2.


Question 16
What is the result of "10 > 5 and 5 < 3"?
 A
True
 B
False
 C
Syntax Error
 D
None of these

Python Keywords
Last Updated : 23 Jul, 2025



Keywords in Python are reserved words that have special meanings and serve
specific purposes in the language syntax. Python keywords cannot be used as the
names of variables, functions, and classes or any other identifier.
Getting List of all Python keywords
We can also get all the keyword names using the below code.
import keyword

# printing all keywords at once using "kwlist()"


print("The list of keywords is : ")

32 | P a g e
print(keyword.kwlist)
Output:
The list of keywords are:
['False', 'None', 'True',"__peg_parser__ 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with',
'yield']
How to Identify Python Keywords ?
 With Syntax Highlighting - Most of IDEs provide syntax-highlight feature. You can
see Keywords appearing in different color or style.
 Look for SyntaxError - This error will encounter if you have used any keyword
incorrectly. Note that keywords can not be used as identifiers (variable or a function
name).
What Happens if We Use Keywords as Variable Names ?
In Python, keywords are reserved words that have special meanings and cannot be
used as variable names. If you attempt to use a keyword as a variable, Python will
raise a SyntaxError. Let's look at an example:
for= 10
print(for)
Output
Hangup (SIGHUP)
File "/home/guest/sandbox/Solution.py", line 1
for = 10
^
SyntaxError: invalid syntax

Suggested Quiz 2.
10 questions
1. Which of the following keywords is used to define a function in Python?
 A
def
 B
func
 C
define
 D
method
Explanation: def is the keyword used to define a function in Python. After def, you specify the function
name, followed by parentheses () and a colon : to start the function's body.
2. What keyword is used to handle exceptions in Python?
 A
except
 B
catch
 C
handle

33 | P a g e
 D
error
Explanation: try is used to define a block of code that might raise an exception. except follows the try
block and defines the code that runs if an exception occurs.
3. Which keyword is used to create a new class in Python?
 A
class
 B
new
 C
def
 D
create
Explanation: class is used to define a new class in Python.
4. In Python, which keyword is used to indicate that a variable is global?
 A
global
 B
public
 C
shared
 D
external
Explanation:
In Python, the keyword global is used to indicate that a variable is global. This keyword is used inside a
function to refer to a variable that is defined in the global scope, allowing the function to modify the global
variable directly.

5. What does the elif keyword do in Python?


 A
It is used to define an exception.
 B
It is used to start a function.
 C
It is used in conditional statements to check additional conditions.
 D
It is used to define a loop.
Explanation: elif is short for "else if" and is used after an if block to check for additional conditions when
the original if condition fails.
6. What keyword is used to return a value from a function in Python?
 A
return
 B
yield
 C
output
 D
send

34 | P a g e
Explanation: The return keyword is used inside a function to send back a result or value to the caller,
effectively ending the function
7. Which of the following keywords is used to define an object constructor in Python?
 A
init
 B
constructor
 C
__init__
 D
define
Explanation:
__init__ is a special method in Python used to initialize an object's state when a new instance of a class is
created.

8. Which of the following keywords is used to declare an alias for a module in Python?
 A
import as
 B
using
 C
alias
 D
import
Explanation: The import as syntax allows you to import a module and give it a shorthand alias, which is
useful for convenience.
9. What keyword is used to define an empty function or class in Python?
 A
continue
 B
skip
 C
pass
 D
break
Explanation: pass is a placeholder keyword that does nothing. It is used in scenarios where we need to
define a function or class but haven’t implemented it yet.
10. Which keyword is used to define an anonymous function in Python?
 A
lambda
 B
def
 C
function
 D
anonymous
Explanation: The lambda keyword is used to create anonymous (unnamed) functions in Python, typically
for short, simple operations.

35 | P a g e
Python Data Types
Last Updated : 12 Jul, 2025



Python Data types are the classification or categorization of data items. It represents
the kind of value that tells what operations can be performed on a particular data.
Since everything is an object in Python programming, Python data types are classes
and variables are instances (objects) of these classes. The following are the standard
or built-in data types in Python:
 Numeric - int, float, complex
 Sequence Type - string, list, tuple
 Mapping Type - dict
 Boolean - bool
 Set Type - set, frozenset
 Binary Types - bytes, bytearray, memoryview

DataTypes
This code assigns variable 'x' different values of few Python data types - int, float,
list, tuple and string. Each assignment replaces the previous value, making 'x' take
on the data type and value of the most recent assignment.
# int, float, string, list and set
x = 50
x = 60.5
x = "Hello World"
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number. These
values are defined as Python int, Python float and Python complex classes in Python.
 Integers - This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.
 Float - This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers - A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example - 2+3j
a=5

36 | P a g e
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

2. Sequence Data Types in Python


The sequence Data Type in Python is the ordered collection of similar or different
Python data types. Sequences allow storing of multiple values in an organized and
efficient fashion. There are several sequence data types of Python:
 Python String
 Python List
 Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there
is no character data type Python, a character is a string of length one. It is represented
by str class.
Strings in Python can be created using single quotes, double quotes or even triple
quotes. We can access individual characters of a String using index.
s = 'Welcome to the Geeks World'
print(s)

# check data type


print(type(s))

# access string with index


print(s[1])
print(s[2])
print(s[-1])

Output
Welcome to the Geeks World
<class 'str'>
e
l
d

37 | P a g e
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets[].
# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed int and string


b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
In order to access the list items refer to the index number. In Python, negative
sequence indexes represent positions from the end of the array. Instead of having to
compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative
indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")


print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
38 | P a g e
Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable. Tuples cannot be
modified after it is created.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated
by a ‘comma’ with or without the use of parentheses for grouping the data sequence.
Tuples can contain any number of elements and of any datatype (like strings, integers,
lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having
one element in the parentheses is not sufficient, there must be a trailing ‘comma’ to
make it a tuple.
# initiate empty tuple
tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)

Output
Tuple with the use of String: ('Geeks', 'For')
Note - The creation of a Python tuple without the use of parentheses is known as
Tuple Packing.
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ]
to access an item in a tuple.
tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items


print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output
1
5
3

3. Boolean Data Type in Python


Python Data type with one of the two built-in values, True or False. Boolean objects
that are equal to True are truthy (true), and those equal to False are falsy (false).
However non-Boolean objects can be evaluated in a Boolean context as well and
determined to be true or false. It is denoted by the class bool.

39 | P a g e
Example: The first two lines will print the type of the boolean values True and False,
which is <class 'bool'>. The third line will cause an error, because true is not a valid
keyword in Python. Python is case-sensitive, which means it distinguishes between
uppercase and lowercase letters.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by a ‘comma’. The
type of elements in a set need not be the same, various mixed-up data type values
can also be passed to the set.
Example: The code is an example of how to create sets using different types of
values, such as strings , lists , and mixed values
# initializing empty set
s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}

Access Set Items


Set items cannot be accessed by referring to an index, since sets are unordered the
items have no index. But we can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in the keyword.
set1 = set(["Geeks", "For", "Geeks"])
print(set1)

40 | P a g e
# loop through set
for i in set1:
print(i, end=" ")

# check if item exist in set


print("Geeks" in set1)

Output
{'Geeks', 'For'}
Geeks For True

5. Dictionary Data Type


A dictionary in Python is a collection of data values, used to store data values like a
map, unlike other Python Data Types that hold only a single value as an element, a
Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it
more optimized. Each key-value pair in a Dictionary is separated by a colon : ,
whereas each key is separated by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable. The dictionary can also be created by the
built-in function dict().
Note - Dictionary keys are case sensitive, the same name but different cases of Key
will be treated distinctly.
# initialize empty dictionary
d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Accessing Key-value in Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used
inside square brackets. Using get() method we can access the dictionary elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key


41 | P a g e
print(d['name'])

# Accessing a element using get


print(d.get(3))

Output
For
Geeks

Python Data Type Exercise Questions


Below are two exercise questions on Python Data Types. We have covered list
operation and tuple operation in these exercise questions. For more exercises on
Python data types visit the page mentioned below.
Q1. Code to implement basic list operations
fruits = ["apple", "banana", "orange"]
print(fruits)
fruits.append("grape")
print(fruits)
fruits.remove("orange")
print(fruits)

Output
['apple', 'banana', 'orange']
['apple', 'banana', 'orange', 'grape']
['apple', 'banana', 'grape']
Q2. Code to implement basic tuple operation
coordinates = (3, 5)
print(coordinates)
print("X-coordinate:", coordinates[0])
print("Y-coordinate:", coordinates[1])

Output
(3, 5)
X-coordinate: 3
Y-coordinate: 5
Quiz: Python Data Type
Related Posts:
 Python int() Function
 float() in Python
 Python complex() Function
 Python Numbers

42 | P a g e
 Python Boolean
 Python String
 Python List
 Python Tuple
 Python Sets
 Dictionaries in Python
 Convert integer to string in Python
 Convert String to Int in Python
 Convert float to exponential
 Convert int to exponential
 Primitive Data Types vs Non Primitive Data Types in Python
Python Data Type
This quiz is designed to test and enhance your knowledge of Python's fundamental data types.
Last Updated : Jan 10, 2025
Question 1
Which of these is not a core data type?
 A
Lists
 B
Dictionary
 C
Tuples
 D
Class
Discuss it

Explanation
Class is a user defined data type
Question 2
What data type is this-> li = [1, 23, ‘hello’, 1]
 A
List
 B
Dictionary
 C
Tuple
 D
Array
Discuss it

Explanation
[ ] defines a list
Question 3
Which of the following function convert a string x to a float in python?
 A
int(x [,base])
 B
long(x [,base] )
 C
43 | P a g e
float(x)
 D
str(x)
Discuss it

Explanation
float(x) − Converts x to a floating-point number
Question 4
Which Python datatype maintains the order of elements inserted?
 A
set
 B
list
 C
dict
 D
Both B and C
Discuss it

Explanation
Lists always maintain insertion order. Starting from Python 3.7, dictionaries (dict) also maintain
the insertion order of keys by default.

Conditional Statements in Python


Last Updated : 23 Jul, 2025



Conditional statements in Python are used to execute certain blocks of code based on
specific conditions. These statements help control the flow of a program, making it
behave differently in different situations.
If Conditional Statement in Python
If statement is the simplest form of a conditional statement. It executes a block of code
if the given condition is true.

If Statement

44 | P a g e
Example:
age = 20

if age >= 18:


print("Eligible to vote.")

Output
Eligible to vote.

Short Hand if
Short-hand if statement allows us to write a single-line if statement.

Example:
age = 19
if age > 18: print("Eligible to Vote.")

Output
Eligible to Vote.
This is a compact way to write an if statement. It executes the print statement if the
condition is true.
If else Conditional Statements in Python
Else allows us to specify a block of code that will execute if the condition(s) associated
with an if or elif statement evaluates to False. Else block provides a way to handle all
other cases that don't meet the specified conditions.

If Else Statement
Example:
age = 10

if age <= 12:


print("Travel for free.")
else:
print("Pay for ticket.")

Output

45 | P a g e
Travel for free.

Short Hand if-else


The short-hand if-else statement allows us to write a single-line if-else statement.
Example:
marks = 45
res = "Pass" if marks >= 40 else "Fail"

print(f"Result: {res}")

Output
Result: Pass
Note: This method is also known as ternary operator. Ternary Operator essentially a
shorthand for the if-else statement that allows us to write more compact and readable
code, especially for simple conditions.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple conditions ,
providing a way to execute different blocks of code based on which condition is true.
Using elif statements makes our code more readable and efficient by eliminating the
need for multiple nested if statements.

Example:
age = 25

if age <= 12:


print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")

Output
Young adult.
The code checks the value of age using if-elif-else. Since age is 25, it skips the first
two conditions (age <= 12 and age <= 19), and the third condition (age <= 35) is True,
so it prints "Young adult.".
46 | P a g e
Nested if..else Conditional Statements in Python
Nested if..else means an if-else statement inside another if statement. We can use
nested if statements to check conditions within conditions.

Nested If Else
age = 70
is_member = True

if age >= 60:


if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")

Output
30% senior discount!

Ternary Conditional Statement in Python


A ternary conditional statement is a compact way to write an if-else condition in a
single line. It’s sometimes called a "conditional expression."
Example:
# Assign a value based on a condition
age = 20
s = "Adult" if age >= 18 else "Minor"

print(s)

Output
Adult
Here:
 If age >= 18 is True, status is assigned "Adult".
 Otherwise, status is assigned "Minor".
Match-Case Statement in Python
match-case statement is Python's version of a switch-case found in other languages. It
allows us to match a variable's value against a set of patterns.
47 | P a g e
Example:
number = 2

match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three
Python Control Flow & Conditional Logic quiz
This quiz is designed to help you master the core concepts of control flow and conditional
statements in Python. These features are essential for making decisions, executing code
conditionally and guiding the logic of your programs.
Question 1 What is the purpose of the if statement in Python?
 A
To define a function
 B
To declare a variable
 C
To execute a block of code conditionally
 D
To create a loop
Explanation
The if statement is used to execute a block of code only if a specified condition is true.
Question 2 Which of the following operators is used for equality comparison in Python?
 A
==
 B
=
 C
===
 D
>
Explanation
The == operator is used for equality comparison.
Question 3 What will be the output of the following code snippet?
x=5
if x > 0:
print("Positive")
else:
print("Negative")

 A
Positive
 B
Negative
 C

48 | P a g e
Zero
 D
Error
Explanation
The code checks if x is greater than 0 and prints "Positive" accordingly.
Question 4 How do you represent the logical AND operator in Python?
 A
&&
 B
and
 C
AND
 D
&
Explanation
The and keyword is used for the logical AND operator in Python.
Question 5 What is the purpose of the elif statement in Python?
 A
To handle exceptions
 B
To create a loop
 C
To define a function
 D
To check additional conditions after the initial if statement
Explanation
The elif statement is used to check additional conditions if the initial if statement is false.
Question 6 In Python, what is the purpose of the else statement within an if-else block?
 A
To define a function
 B
To check additional conditions
 C
To execute a block of code when the if condition is false
 D
To create a loop
Explanation
The else statement is executed when the if condition is false.
Question 7 What is the output of the following code snippet?
x = 10
if x > 5:
print("Greater than 5")
elif x > 8:
print("Greater than 8")
else:
print("Less than or equal to 5")

 A
Greater than 5
 B

49 | P a g e
Greater than 8
 C
Less than or equal to 5
 D
No output
Explanation
The first condition (x > 5) is true, so "Greater than 5" is printed.
Question 8 Which statement is used to exit a loop prematurely in Python?
 A
break
 B
exit
 C
return
 D
continue
Explanation
The break statement is used to exit a loop prematurely.
Question 9 In Python, what is the purpose of the try-except block?
 A
To create a loop
 B
To check multiple conditions
 C
To handle exceptions
 D
To define a function
Explanation
The try-except block is used to handle exceptions in Python.
Question 10 What is the output of the following code snippet?
for i in range(5):
if i == 3:
continue
print(i)

 A
01234
 B
0124
 C
012
 D
0123
Explanation
The continue statement skips the iteration when i is 3.

Python for Loops


50 | P a g e

Python For Loops are used for iterating over a sequence like lists, tuples, strings,
and ranges.
 For loop allows you to apply the same operation to every item within loop.
 Using For Loop avoid the need of manually managing the index.
 For loop can iterate over any iterable object, such as dictionary, list or any custom
iterators.
For Loop Example:

s = ["Geeks", "for", "Geeks"]

# using for loop with string


for i in s:
print(i)

Output
Geeks
for
Geeks

Table of Content
 Python For Loop with String
 Using range() with For Loop
 Control Statements [Continue, Break, Pass, Else]
 Using Enumerate with for loop
 Nested For Loops
Flowchart of Python For Loop

For Loop flowchart

51 | P a g e
Python For Loop Syntax
for var in iterable:
# statements
pass
Note: In Python, for loops only implement the collection-based iteration.
Python For Loop with String
This code uses a for loop to iterate over a string and print each character on a new
line. The loop assigns each character to the variable i and continues until all
characters in the string have been processed.

s = "Geeks"
for i in s:
print(i)

Output
G
e
e
k
s

Using range() with For Loop


The range() function is commonly used with for loops to generate a sequence of
numbers. It can take one, two, or three arguments:
 range(stop): Generates numbers from 0 to stop-1.
 range(start, stop): Generates numbers from start to stop-1.
 range(start, stop, step): Generates numbers from start to stop-1, incrementing by
step.
for i in range(0, 10, 2):
print(i)

Output
0
2
4
6
8

Control Statements with For Loop


Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.
52 | P a g e
Continue with For Loop
Python continue Statement returns the control to the beginning of the loop.

# Prints all letters except 'e' and 's'

for i in 'geeksforgeeks':

if i == 'e' or i == 's':
continue
print(i)

Output
g
k
f
o
r
g
k

Break with For Loop


Python break statement brings control out of the loop.

for i in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
if i == 'e' or i == 's':
break

print(i)

Output
e

Pass Statement with For Loop


The pass statement to write empty loops. Pass is also used for empty control
statements, functions, and classes.

# An empty loop
for i in 'geeksforgeeks':
pass
print(i)

Output
53 | P a g e
s

Else Statement with For Loops


Python also allows us to use the else condition for loops. The else block just after
for/while is executed only when the loop is NOT terminated by a break statement.

for i in range(1, 4):


print(i)
else: # Executed because no break in for
print("No Break\n")

Output
1
2
3
No Break

Using Enumerate with for loop


In Python, enumerate() function is used with the for loop to iterate over an iterable
while also keeping track of index of each item.

li = ["eat", "sleep", "repeat"]

for i, j in enumerate(li):
print (i, j)

Output
0 eat
1 sleep
2 repeat

Nested For Loops in Python


This code uses nested for loops to iterate over two ranges of numbers (1 to 3
inclusive) and prints the value of i and j for each combination of these two loops. \
The inner loop is executed for each value of i in outer loop. The output of this code will
print the numbers from 1 to 3 three times, as each value of i is combined with each
value of j.

for i in range(1, 4):


for j in range(1, 4):
print(i, j)

Output

54 | P a g e
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Python For Loop Exercise Questions


Below are two Exercise Questions on Python for-loops. We have covered continue
statement and range() function in these exercise questions.
Q1. Code to implement Continue statement in for-loop

a = ["shirt", "sock", "pants", "sock", "towel"]


b = []
for i in a:
if i == "sock":
continue
else:
print(f"Washing {i}")
b.append("socks")
print(f"Washing {b}")

Output
Washing shirt
Washing pants
Washing towel
Washing ['socks']
Q2. Code to implement range function in for-loop

for i in range(1, 8):


d = 3 + (i - 1) * 0.5
print(f"Day {i}: Run {d:.1f} miles")

Output
Day 1: Run 3.0 miles
Day 2: Run 3.5 miles
Day 3: Run 4.0 miles

55 | P a g e
Day 4: Run 4.5 miles
Day 5: Run 5.0 miles
Day 6: Run 5.5 miles
Day 7: Run 6.0 miles

Python for loop quiz


Question 1 What is the purpose of a for loop in Python?
 A
To define a function
 B
To iterate over a sequence or iterable
 C
To create a conditional statement
 D
To perform arithmetic operations
Explanation The primary purpose of a for loop is to iterate over a sequence or iterable,
executing a block of code for each iteration.
Question 2 How is the range function typically used in a for loop?
 A
range(start, end)
 B
range(end)
 C
range(start, end, step)
 D
range(step)
Explanation The range function is commonly used with a for loop to generate a sequence of
numbers with a specified start, end, and step.
Question 3 In a for loop, how can you access both the index and the value of each element in a
list?
 A
Using a while loop
 B
Using the enumerate function
 C
Using the index method
 D
Using the iter function
Explanation The enumerate function is used to iterate over both the index and the value of
elements in a list.
Question 4 What will the following code output?
for i in range(3):
print(i, end =' ')

 A
012
 B
123

56 | P a g e
 C
0123
 D
1234
Explanation The code prints values from 0 to 2 (inclusive) due to the range(3) used in the for
loop.
Question 5 How can you iterate over the elements of a list in reverse order using a for loop?
 A
Using the reversed function
 B
Using the reverse method
 C
Using a negative step in the range function
 D
Python doesn't support iterating in reverse order
Explanation By using a negative step in the range function, you can iterate over the elements
of a list in reverse order.
Question 6 What is the purpose of the continue keyword in a for loop?
 A
To exit the loop
 B
To skip the remaining code and move to the next iteration
 C
To restart the loop from the beginning
 D
To print the current iteration and continue
Explanation The continue keyword is used to skip the remaining code inside the loop and
move to the next iteration.
Question 7 What is the difference between a for loop and a while loop?
 A
For loops iterate over sequences, while while loops run based on a condition.
 B
For loops are better than while loop.
 C
They are not interchangeable.
 D
For loop is faster than while loop.
Explanation
 For loops iterate over a sequence (iterables).
 While loops repeat as long as a condition is True.
 Both can be used for iteration, but for loops are more concise with known sequences.
Question 8 What is the purpose of the pass statement in a for loop?
 A
To terminate the loop
 B
To create an infinite loop
 C
To skip the current iteration and move to the next
 D
To do nothing and continue to the next iteration
57 | P a g e
Explanation The pass statement is a no-operation statement used when a statement is
syntactically required but no action is desired.
Question 9 How can you iterate over the keys and values of a dictionary using a for loop?
 A
for key, value in dictionary.items():
 B
for key in dictionary.keys():
 C
for key in dictionary:
 D
for value in dictionary.values():
Explanation In Python, to iterate over both the keys and values of a dictionary, you can use
the items() method, which returns a view of the dictionary's key-value pairs. Here's how you do
it:

for key, value in dictionary.items():

Question 10 What is the significance of the break and else combination in a for loop?
 A
Executes else only if loop wasn't exited by break.
 B
It is a syntax error; break and else cannot be used together.
 C
It skips the current iteration.
 D
It restarts the loop.
Explanation The else block after a for loop executes only if the loop completes without a break.
If break runs, else is skipped.
Question 11 How do you iterate over the characters of a string using a for loop?
 A
for char in string:
 B
for i in range(len(string)):
 C
for i, char in enumerate(string):
 D
for i in string:
Explanation Using a for loop directly iterates over the characters of a string.
Question 12 What will the following code output?
for i in range(5):
print(i, end=' ')

 A
01234
 B
12345
 C
0123
 D

58 | P a g e
1234
Explanation The code prints values from 0 to 4 using the range(5) in the for loop.
Question 13 What is the purpose of the range function in a for loop?
 A
To create a list of numbers
 B
To define the start and end of the loop
 C
To generate a sequence of numbers
 D
To specify the step size of the loop
Explanation The range function is used to generate a sequence of numbers that can be
iterated over in a for loop.
Question 14 What is the output of the following code?
total = 0
for num in range(1, 6):
total += num
print(total)
 A
10
 B
11
 C
15
 D
5
Explanation The code calculates the sum of numbers from 1 to 5 and prints the total.
Question 15 What will the following code output?
for i in range(3):
for j in range(2):
print(i, j)

 A
(0, 0) (0, 1) (1, 0) (1, 1) (2, 0) (2, 1)
 B
012012
 C
001122
 D
001112
Explanation The nested for loop prints combinations of i and j.
Question 16 How can you iterate over a tuple using a for loop?
 A
for element in tuple:
 B
for in in range(len(tuple)):
 C
for i, element in enumerate(tuple):
 D
for i in tuple:

59 | P a g e
Explanation Using a for loop directly iterates over the elements of a tuple.
Question 17 How can you iterate over the indices and values of a list using a for loop?
 A
for i, value in enumerate(list):
 B
for index, value in list:
 C
for index in list.index():
 D
for value in list.values():
Explanation enumerate() provides both index and value during iteration.
Question 18 What will the following code output?
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers) - 1, -1, -1):
print(numbers[i], end=' ')

 A
54321
 B
12345
 C
55555
 D
135
Explanation The code prints the elements of the list in reverse order.
Question 19 What will the following code output?
numbers = [1, 2, 3, 4, 5]
for i, num in enumerate(numbers):
if i % 2 == 0:
continue
print(num, end=' ')
 A
135
 B
24
 C
12345
 D
01234
Explanation The code skips printing elements at even indices (i % 2 == 0), so only odd-
indexed elements are printed.
Question 20 What will the following code output?
for char in 'hello':
if char == 'l':
break
print(char, end=' ')

 A
he
 B
hel
60 | P a g e
 C
hell
 D
hello
Explanation The code prints 'h' and 'e' and terminates when 'l' is encountered due to the break
statement.
Question 21 What is the purpose of the else clause in a for loop?
 A
To execute an alternative block of code
 B
To handle exceptions
 C
To specify the step size of the loop
 D
To execute code when the loop is terminated normally
Explanation The else clause is executed when the loop completes its iterations without
encountering a break statement.
Question 22 What will the following code output?
numbers = [3, 7, 2, 8, 5]
for i, num in enumerate(numbers):
if i == num:
break
print(num, end=' ')
 A
37285
 B
37
 C
372
 D
728
Explanation- The loop breaks when the index matches the value, so it stops at i == 2, printing
3 7 2.
Question 23. How can you iterate over a string in reverse order using a for loop?
 A
for char in reversed(string):
 B
for char in string[::-1]:
 C
for char in string.reverse():
 D
Reverse iteration is not possible on strings
Explanation -The reversed function can be used to iterate over a string in reverse order.
Question 24 What is the purpose of the enumerate function in a for loop?
 A
To create an enumerated list
 B
To generate a sequence of numbers
 C
To iterate over two lists simultaneously

61 | P a g e
 D
To access both the index and the value of elements in an iterable
Explanation The enumerate function is used to iterate over both the index and the value of
elements in an iterable.
Python Loops-2
Loops in Python are used to execute a block of code repeatedly, either for a specified number of
times or while a condition is true. They help automate repetitive tasks and simplify code.
Question 1. In programming, what is an iteration?
 A
The repetition of steps within a program.
 B
The order in which instructions are carried out
 C
A decision point in a program
 D
Testing a program to make sure it works
Explanation- Hint: Iteration refers to repetition of steps within a program
Question 2. To solve a problem that requires the user to enter 10 numbers would use what type of
iteration?
 A
Switch
 B
For loop
 C
If
 D
Else
Explanation- For loop as we know the statement is to be executed 10 times
Question 3. What will be the output of the following code?
d = {0, 1, 2}
for x in d:
print(x)
 A
012
 B
{ 0, 1, 2} { 0, 1, 2}{ 0, 1, 2}
 C
Error
 D
No output
Explanation- Loops over the elements of the set and prints them.
Question 4. What is the output of the following code?
True = False
while True:
print(True)
break
 A
True
 B
False
62 | P a g e
 C
1
 D
None of the above
Explanation- Syntax error, as True is a reserved word.
Question 5. What is the output of the following nested loop?
n = [10, 20]
li = ["Chair", "Table"]

for x in n:
for y in li:
print(x, y)
 A
10 Chair
10 Table
 B
10 Chair
10 Table
20 Chair
20 Table
 C
Error
 D
No output
Question 6. What is the value of the var after the for loop completes its execution?
var = 10
for i in range(10):
for j in range(2,10,1):
if var % 2 == 0:
continue
else:
var += 1
print(var)
 A
20
 B
10
 C
30
 D
14
Explanation- Since var is even (10), the continue statement skips all updates inside the loop
every time. As a result, var remains unchanged at 10 after the loops.
Question 7. What is the output of the following nested loop?
for num in range(10, 14):
for i in range(2, num):
if num%i == 1:
print(num)
break

 A
10

63 | P a g e
11
12
13
 B
12
14
 C
Error
 D
No output
Explanation-Hint: We use a break statement to terminate the loop and transfer execution to the
statement immediately following the loop.
Question 8. What is the output of the following code?
X=5;
while X>0:
X=X-1;
print(X)
 A
5
4
3
2
1
0
 B
4
3
2
1
0
 C
5 4 3 2 1
 D
4 3 2 1 0
Explanation-The first iteration makes X as 4 after decrement and the answer is always printed
on a new line.
Question 9. What is the value of x?
x=0
while (x < 100):
x+=2
print(x)
 A
101
 B
99
 C
98
 D
100
Explanation-The loop terminates as x gets to 100.

64 | P a g e
Question 10. The best command to repeat a control statement a fixed number of times?
 A
While loop
 B
For loop
 C
If
 D
Else
Explanation- "for" loop is specifically designed to run a block of code a fixed number of times,
especially when using functions like range(). While a "while" loop can also repeat code, it is
better suited for situations where the number of iterations is not known in advance.
Question 11. What is the output of the following code?
while True:
print(“Geeks!”)
break;
 A
Geeks!
 B
“Geeks!”
 C
‘Geeks!’
 D
Geeks!
Geeks!
Geeks!
(Repeated infinite times)
Explanation- The break statement executes the very first time and terminates the loop after the
first iteration.
Question 12. What is the output of the following code?
i=1
while True:
if i%7 == 0:
break
print(i, end=" ")
i += 1
 A
123456
 B
1234567
 C
No output
 D
Error
Explanation- Control exits the loop when i becomes 7.
Question 13. The character that must be at the end of the line for if, while, for etc.
 A
:
 B
;
 C

65 | P a g e
,
 D
.
Question 14. Which two statements are used to implement iteration?
 A
IF and WHILE
 B
IF and FOR
 C
FOR and WHILE
 D
IF and ELSE
Explanation -Hint: For and while are used to implement iteration. If and else are used to check
conditions.
Question 15. Which type of loop continues to iterate until explicitly instructed to stop?
 A
For loop
 B
While loop
 C
For-each loop
 D
None of the above
Explanation- A while loop keeps iterating as long as the condition is true and can be stopped
using instructions like break. It continues running until explicitly instructed to stop.
Question 16. What is the output of the following code?
while True:

print(“Geeks!”)
 A
Geeks!
 B
“Geeks!”
 C
‘Geeks!’
 D
Geeks!
Geeks!
Geeks!
(Repeated infinite times)
Explanation This is an infinite loop as the condition is always true.
Question 17. What will be the output of the following code?
x="GFG"
for i in range(x):
print(i)
 A
GFG
 B
012
 C
Error

66 | P a g e
 D
No output
Explanation-range(str) doesn’t exist.
Question 18 What will be the output of the following Python code?
x = 'abcd'
for i in range(len(x)):
print(i, end= " ")
 A
1234
 B
0123
 C
Error
 D
No output
Explanation-length(str) of the string is 4.
Question 19 What will be the output of the following Python code?
for i in range(int(2.0)):
print(i)
 A
0.0 1.0
 B
01
 C
Error
 D
0
1
Explanation-range(int(2.0)) is the same as range(2).

2. Python Functions
Python Functions are the backbone of organized and efficient code in Python. Here,
in this section of Python 3 tutorial we'll explore their syntax, parameter handling,
return values and variable scope. From basic concepts to advanced techniques like
closures and decorators. Along the way, we'll also introduce versatile functions like
range(), map, filter and lambda functions.
 Python Functions
 Pass Statement in Function
 Global and Local Variables
 Recursion in Python
 *args and **kwargs in Function
 ‘Self’ as Default Argument
 First Class Function
 Lambda Function
67 | P a g e
 Map, Reduce and Filter Function
 Inner Function
 Decorators
 Quiz: Functions
Definition2
Python Functions


Python Functions is a block of statements that does a specific task. The idea is to
put some commonly or repeatedly done task together and make a function so that
instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.
Benefits of Using Functions
 Code Reuse
 Reduced code length
 Increased redability of code
Python Function Declaration
The syntax to declare a function is:

S
yntax of Python Function Declaration

Types of Functions in Python


Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that are
available to use.
 User-defined function: We can create our own functions based on our
requirements.

68 | P a g e
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require.
What is def ?
The def keyword stands for define. It is used to create a user-defined function. It
marks the beginning of a function block and allows you to group a set of statements so
they can be reused when the function is called.
Syntax:
def function_name(parameters):
# function body
Explanation:
 def: Starts the function definition.
 function_name: Name of the function.
 parameters: Inputs passed to the function (inside ()), optional.
 : : Indicates the start of the function body.
 Indented code: The function body that runs when called.
Example: Let’s understand this with a simple example. Here, we define a function
using def that prints a welcome message when called.

def fun():
print("Welcome to GFG")
For more information, refer to this article: Python def Keyword
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions
Python followed by parenthesis containing parameters of that particular function.
Below is the example for calling def function Python.

def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

Output
Welcome to GFG

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function
can have any number of arguments separated by a comma.
Syntax for functions with arguments:
def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression

69 | P a g e
data_type and return_type are optional in function declaration, meaning the same
function can also be written as:
def function_name(parameter) :
"""Docstring"""
# body of the function
return expression
Let's understand this with an example, we will create a simple function in Python to
check whether the number passed as an argument to the function is even or odd.

def evenOdd(x: int) ->str:


if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Output
Even
Odd
The above function can also be declared without type_hints, like this:

def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Output
Even
Odd

Types of Python Function Arguments


Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following function argument types in Python:
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)
Let's discuss each type in detail.

70 | P a g e
Default Arguments
A default argument is a parameter that assumes a default value if a value is not
provided in the function call for that argument. The following example illustrates
Default arguments to write functions in Python.

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

myFun(10)

Output
x: 10
y: 50
Like C++ default arguments, any number of arguments in a function can have a
default value. But once we have a default argument, all the arguments to its right must
also have default values.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the
caller does not need to remember the order of parameters.

def student(fname, lname):


print(fname, lname)

student(fname='Geeks', lname='Practice')
student(lname='Practice', fname='Geeks')

Output
Geeks Practice
Geeks Practice

Positional Arguments
We used the Position argument during the function call so that the first argument (or
value) is assigned to name and the second argument (or value) is assigned to age. By
changing the position, or if you forget the order of the positions, the values can be
used in the wrong places, as shown in the Case-2 example below, where 27 is
assigned to the name and Suraj is assigned to the age.

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)

print("Case-1:")

71 | P a g e
nameAge("Suraj", 27)

print("\nCase-2:")
nameAge(27, "Suraj")

Output
Case-1:
Hi, I am Suraj
My age is 27

Case-2:
Hi, I am 27
My age is Suraj

Arbitrary Keyword Arguments


In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable
number of arguments to a function using special symbols. There are two special
symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
Hello
Welcome
to
GeeksforGeeks
Example 2: Variable length keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

myFun(first='Geeks', mid='for', last='Geeks')

72 | P a g e
Output
first == Geeks
mid == for
last == Geeks

Docstring
The first string after the function is called the Document string or Docstring in short.
This is used to describe the functionality of the function. The use of docstring in
functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function

def evenOdd(x):
"""Function to check if the number is even or odd"""

if(x % 2 == 0):
print("even")
else:
print("odd")

print(evenOdd.__doc__)

Output
Function to check if the number is even or odd

Python Function within Functions


A function that is defined inside another function is known as the inner
function or nested function. Nested functions can access variables of the enclosing
scope. Inner functions are used so that they can be protected from everything
happening outside the function.

def f1():
s = 'I love GeeksforGeeks'

def f2():
print(s)

f2()

f1()

Output
I love GeeksforGeeks

73 | P a g e
Anonymous Functions in Python
In Python, an anonymous function means that a function is without a name. As we
already know the def keyword is used to define the normal functions and the lambda
keyword is used to create anonymous functions.

def cube(x): return x*x*x # without lambda

cube_l = lambda x : x*x*x # with lambda

print(cube(7))
print(cube_l(7))

Output
343
343

Return Statement in Python Function


The return statement in Python is used to exit a function and send a value back to the
caller. It can return any data type, and if multiple values are separated by commas,
they are automatically packed into a tuple. If no value is specified, the function
returns None by default.
Syntax:
return [expression]
Explanation:
 return: Ends the function and optionally sends a value to the caller.
 [expression]: Optional value to return, defaults to None if omitted.
Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output
4
16
For more information, refer to this article: Python return statement
Pass by Reference and Pass by Value
One important thing to note is, in Python every variable name is a reference. When we
pass a variable to a function Python, a new reference to the object is created.
Parameter passing in Python is the same as reference passing in Java.

74 | P a g e
# Here x is a new reference to same list lst
def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output
[20, 11, 12, 13, 14, 15]
When we pass a reference and change the received reference to something else, the
connection between the passed and received parameters is broken. For example,
consider the below program as follows:

def myFun(x):
x = [20, 30, 40]

lst = [10, 11, 12, 13, 14, 15]


myFun(lst)
print(lst)

Output
[10, 11, 12, 13, 14, 15]
Another example demonstrates that the reference link is broken if we assign a new
value (inside the function

def myFun(x):
x = 20

x = 10
myFun(x)
print(x)

Output
10
Exercise: Try to guess the output of the following code.

def swap(x, y):


temp = x
x=y
y = temp

75 | P a g e
x=2
y=3
swap(x, y)
print(x)
print(y)

Output
2
3

Recursive Functions in Python


Recursion in Python refers to when a function calls itself. There are many instances
when you have to build a recursive function to solve Mathematical and Recursive
Problems.
Using a recursive function should be done with caution, as a recursive function can
become like a non-terminating loop. It is better to check your exit statement while
creating a recursive function.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output
24
Here we have created a recursive function to calculate the factorial of the number. It
calls itself until a base case (n==0) is met.
Quiz:
 Python Functions Quiz
Python Functions
Question 1. What will be the output of the following code :
print(type(type(int)))

 A
type \'int\'
 B
type \'type\'
 C
Error
 D
0

76 | P a g e
Explanation- The type() function returns the class of the argument the object belongs to. Thus,
type(int) returns which is of the type ‘type’ object.
Question 2. What is the output of the following code :
li = ['a', 'b', 'c', 'd']
print("".join(li))
 A
Error
 B
None
 C
abcd
 D
[‘a’,’b’,’c’,’d’]
Explanation- “” depicts a null string and the join function combines the elements of the list into
a string.
Question 3. What is the output of the following segment :
print(chr(ord('A')))
 A
A
 B
B
 C
a
 D
Error
Explanation- ord() function converts a character into its ASCII notation and chr() converts the
ASCII to character.
Question 4. What is the output of the following program :
y=8
z = lambda x : x * y
print(z(6))
 A
48
 B
14
 C
64
 D
None of the above
Explanation- Lambda multiplies input by outer scope variable y = 8, so z(6) is 6*8 = 48.
Question 5. What is called when a function is defined inside a class?
 A
Module
 B
Class
 C
Another Function
 D
Method

77 | P a g e
Explanation- When a function is defined inside a class then it is called Method. The method is
accessible to data that is contained within the class.
Question 6. Which of the following is the use of id() function in python?
 A
Id returns the identity of the object
 B
Every object doesn’t have a unique id
 C
All of the mentioned
 D
None of the mentioned
Explanation- Each object in Python has a unique id. The id() function returns the object’s id.
Question 7. What is the output of the following program :
def func(a, b=[]):
b.append(a)
return b

print(func(1))
print(func(2))
 A
[1]
[2]

 B
[1]
[1, 2]

 C
[1]
[1]

 D
None of the above
Explanation- In Python, default mutable arguments like lists retain their state across function
calls. The list b is initialized only once when the function is defined, not each time it's called.
Therefore:
 func(1) appends 1 to the default list b, resulting in [1].
 func(2) appends 2 to the same list b, which already contains [1], resulting in [1, 2].
This behavior can lead to unexpected results if not carefully managed. To avoid this, it's
common practice to use None as the default value and initialize the list inside the function:
def func(a, b=None):
b.append(a)
return b

print(func(1))
print(func(2))

Question 8. Suppose li is [3, 4, 5, 20, 5, 25, 1, 3], what is li after li.pop(1)?


 A

78 | P a g e
[3, 4, 5, 20, 5, 25, 1, 3]
 B
[1, 3, 3, 4, 5, 5, 20, 25]
 C
[3, 5, 20, 5, 25, 1, 3]
 D
[1, 3, 4, 5, 20, 5, 25]
Explanation- pop(i) removes the ith index element from the list
Question 9. time.time() returns ________
 A
The current time as a string formatted as "HH:MM:SS".
 B
The current time in milliseconds since January 1, 1970 UTC (Unix epoch).
 C
The current time in seconds (including fractions) since January 1, 1970 UTC (Unix epoch).
 D
The system’s local time in seconds since midnight.

Explanation- time.time() returns the number of seconds as a floating-point number that have
elapsed since the Unix epoch (January 1, 1970, UTC). This value includes fractional seconds to
provide precision. It does not return milliseconds or a formatted string, nor does it return local
time since midnight.
Question 10. What will be the output of the following code?
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner

closure = outer()
print(closure())
print(closure())

 A
15
20
 B
15
15
 C
10
15
 D
5
5

Explanation-The nonlocal keyword allows modification of x inside the inner function, which
maintains state between function calls.
79 | P a g e
Python pass Statement


Pass statement in Python is a null operation or a placeholder. It is used when a


statement is syntactically required but we don't want to execute any code. It does
nothing but allows us to maintain the structure of our program.
Example Use of Pass Keyword in a Function
Pass keyword in a function is used when we define a function but don't want to
implement its logic immediately. It allows the function to be syntactically valid,
even though it doesn't perform any actions yet.

# Example of using pass in an empty function


def fun():
pass # Placeholder, no functionality yet

# Call the function


fun()
Explanation:
 function fun() is defined but contains the pass statement, meaning it does nothing
when called.
 program continues execution without any errors and the message is printed after
calling the function.
Let's explore other methods how we can use python pass statement:
Table of Content
 Using pass in Conditional Statements
 Using pass in Loops
 Using pass in Classes
Using pass in Conditional Statements
In a conditional statement (like an if, elif or else block), the pass statement is used
when we don't want to execute any action for a particular condition.

x = 10

if x > 5:
pass # Placeholder for future logic
else:
print("x is 5 or less")

Output
Explanation:

80 | P a g e
 When x > 5, the pass statement is executed, meaning nothing happens.
 If x <= 5, the else block runs, printing "x is 5 or less".
 pass allows the code to compile and run without errors, even though the if block is
currently empty.
Using pass in Loops
In loops (such as for or while), pass can be used to indicate that no action is required
during iterations.

for i in range(5):
if i == 3:
pass # Do nothing when i is 3
else:
print(i)

Output
0
1
2
4
Explanation:
 The loop iterates through numbers from 0 to 4.
 When i == 3, the pass statement is executed, meaning no action is taken for that
iteration.
 For other values of i, the number is printed.
Using pass in Classes
In classes, pass can be used to define an empty class or as a placeholder for
methods that we intend to implement later.

class EmptyClass:
pass # No methods or attributes yet

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
pass # Placeholder for greet method

# Creating an instance of the class


p = Person("Anurag", 30)
Explanation:
 EmptyClass is defined but has no methods or attributes. The pass statement is
used to define an empty class.

81 | P a g e
 In the Person class, the greet method is defined, but it does nothing yet (as
indicated by pass).
 This allows us to define the class and method structure without having to
implement the logic immediately.
Global and Local Variables in Python

In Python, global variables are declared outside any function and can be accessed
anywhere in the program, including inside functions. On the other hand, local
variables are created within a function and are only accessible during that
function’s execution. This means local variables exist only inside the function where
they are defined and cannot be used outside it. Let’s understand each in detail.
Python Local Variables
Local variables are created within a function and exist only during its execution.
They're not accessible from outside the function.
Example 1: In this example, we are creating and accessing a local variable inside a
function.

def greet():
msg = "Hello from inside the function!"
print(msg)

greet()

Output
Hello from inside the function!
Explanation: We define greet() with a local variable msg and print it. Since msg
exists only during the function's execution, it's accessed within the function.
Calling greet() displays the message.
Example 2: In this example, we are creating a local variable inside a function and then
trying to access it outside the function, which causes an error.
def greet():
msg = "Hello!"
print("Inside function:", msg)

greet()
print("Outside function:", msg)
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 6, in <module>

82 | P a g e
print("Outside function:", msg)
^^^
NameError: name 'msg' is not defined
Explanation: msg is a local variable inside greet() and can only be accessed there.
Printing it outside causes an error because it doesn't exist globally.
Python Global Variables
Global variables are defined outside all functions. They can be accessed and used in
any part of the program, including inside functions.
Example 1: In this example, we are creating a global variable and then accessing it
both inside and outside a function.

msg = "Python is awesome!"

def display():
print("Inside function:", msg)

display()
print("Outside function:", msg)

Output
Inside function: Python is awesome!
Outside function: Python is awesome!
Explanation: msg is a global variable accessible both inside and outside
the display() function. Calling display() prints the global msg and
printing msg outside the function works as expected.
Example 2: In this example, we're creating a global variable and then using it both
inside and outside a function.

def fun():
print("Inside Function", s)

# Global scope
s = "I love Geeksforgeeks"
fun()
print("Outside Function", s)

Output
Inside Function I love Geeksforgeeks
Outside Function I love Geeksforgeeks
Explanation: s is a global variable accessed and printed inside fun(). Both
calling fun() and printing s outside show the same global value.
Note: As there are no locals, the value from the globals will be used but make sure
both the local and the global variables should have same name.
Why do we use Local and Global variables in Python?
83 | P a g e
If a variable is defined both globally and locally with the same name, the local variable
shadows the global variable inside the function. Changes to the local variable do not
affect the global variable unless you explicitly declare the variable as global. Example:

def fun():
s = "Me too."
print(s)

s = "I love Geeksforgeeks"


fun()
print(s)

Output
Me too.
I love Geeksforgeeks
Explanation: Inside fun(), s is a local variable set to "Me too." and prints that value.
Outside, the global s remains "I love Geeksforgeeks", so printing s afterward shows
the global value.
What if We Try to Modify a Global Variable Inside a
Function?
Attempting to change a global variable inside a function without declaring it as global
will cause an error. Example:
def fun():
s += 'GFG'
print("Inside Function", s)

s = "I love Geeksforgeeks"


fun()
Output
UnboundLocalError: local variable 's' referenced before assignment
Explanation: fun() tries to modify s without declaring it global, so Python treats s as
local but it’s used before assignment, causing an error. Declaring s as global
inside fun() fixes this.
Modifying Global Variables Inside a Function
To modify a global variable inside a function, you must explicitly tell Python that you
want to use the global version by using the global keyword. Example:

def fun():
global s
s += ' GFG' # Modify the global variable
print(s)
s = "Look for Geeksforgeeks Python Section"
print(s)

s = "Python is great!"
fun()

84 | P a g e
print(s)

Output
Python is great! GFG
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section
Explanation: Inside fun(), the global keyword lets Python modify the global
variable s directly. The function first appends ' GFG' to "Python is great!", then
reassigns s to "Look for Geeksforgeeks Python Section".
Example 2: This example demonstrates how Python handles global and local
variables with the same name, and how the global keyword affects their behavior.

a = 1 # Global variable

def f():
print('f():', a) # Uses global a

def g():
a = 2 # Local variable shadows global
print('g():', a)

def h():
global a
a = 3 # Modifies global a
print('h():', a)

print('global:', a)
f()
print('global:', a)
g()
print('global:', a)
h()
print('global:', a)

Output
global: 1
f(): 1
global: 1
g(): 2
global: 1
h(): 3
global: 3
Explanation:
85 | P a g e
 f() prints the global a without changing it.
 g() creates a local a that shadows the global one, leaving the global a unchanged.
 h() uses global to modify the global a.
 Only h() changes the global variable, f() and g() do not.

Recursion in Python


Recursion involves a function calling itself directly or indirectly to solve a problem by


breaking it down into simpler and more manageable parts. In Python, recursion is
widely used for tasks that can be divided into identical subtasks.
In Python, a recursive function is defined like any other function, but it includes a call
to itself. The syntax and structure of a recursive function follow the typical function
definition in Python, with the addition of one or more conditions that lead to the
function calling itself.
Basic Example of Recursion:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

print(factorial(5))

Output
120
Explanation: The factorial of a number n (denoted as n!) is the product of all positive
integers less than or equal to n. The recursive approach involves the function calling
itself with a decremented value of n until it reaches the base case of 1.
Let's understand recursion in python deeply:
Basic Structure of Recursive Function
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)

Base Case and Recursive Case


86 | P a g e
 Base Case: This is the condition under which the recursion stops. It is crucial to
prevent infinite loops and to ensure that each recursive call reduces the problem in
some manner. In the factorial example, the base case is n == 1.
 Recursive Case: This is the part of the function that includes the call to itself. It
must eventually lead to the base case. In the factorial example, the recursive case
is return n * factorial(n-1).
Example:

def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))

Output
55
Explanation:
 Base Cases: If n == 0, the function returns 0. If n == 1, the function returns 1.
These two cases are necessary to stop the recursion.
 Recursive Case: The function calls itself twice with the decrements of n (i.e.,
fibonacci(n-1) and fibonacci(n-2)), summing the results of these calls. This division
into smaller subproblems continues until the base cases are reached.
Types of Recursion in Python
Recursion can be broadly classified into two types: tail recursion and non-tail
recursion. The main difference between them is related to what happens after the
recursive call.
 Tail Recursion: This occurs when the recursive call is the last operation executed
in the function, with no additional work or calculation following the recursive call. In
many programming languages, tail recursion can be optimized by the compiler into
iterative loops to improve performance and prevent stack overflow.
 Non-Tail Recursion: This occurs when there are operations or calculations that
follow the recursive call. This type prevents the compiler or interpreter from
optimizing the recursion into an iteration.
Here is a Python example that demonstrates both tail recursion and non-tail recursion:

def tail_fact(n, acc=1):


# Base case
if n == 0:
return acc
# Tail recursive call with an accumulator
else:
return tail_fact(n-1, acc * n)

87 | P a g e
def nontail_fact(n):
# Base case
if n == 1:
return 1
# Non-tail recursive call because the multiplication happens after the call
else:
return n * nontail_fact(n-1)

# Example usage
print(tail_fact(5))
print(nontail_fact(5))

Output
120
120

*args and **kwargs in Python




In Python, *args and **kwargs are used to allow functions to accept an arbitrary
number of arguments. These features provide great flexibility when designing
functions that need to handle a varying number of inputs.
Example:

# *args example
def fun(*args):
return sum(args)

print(fun(1, 2, 3, 4))
print(fun(5, 10, 15))

# **kwargs example
def fun(**kwargs):
for k, val in kwargs.items():
print(k, val)

fun(a=1, b=2, c=3)

Output
10

88 | P a g e
30
a 1
b 2
c 3
Let's explore *args and **kwargs in detail:
Table of Content
Python *args?

 Python **kwargs?
 Using both *args and **kwargs in Python
There are two special symbols to pass multiple arguments:

*args and **kwargs in Python


Special Symbols Used for passing arguments in Python:
 *args (Non-Keyword Arguments)
 **kwargs (Keyword Arguments)
Note: “We use the "wildcard" or "*" notation like this - *args OR **kwargs - as our
function's argument when we have doubts about the number of arguments we should
pass in a function.”
Python *args
The special syntax *args in function definitions is used to pass a variable number of
arguments to a function. It is used to pass a non-keyworded, variable-length argument
list. These arguments are grouped into a tuple, allowing the function to handle any
number of inputs.
For example, a multiply() function can use *args to accept any number of inputs and
multiply them. The * makes the variable iterable, so it can be looped through or used
with functions like map() and filter().

89 | P a g e
Example 1:
Python program to illustrate *args for a variable number of arguments

def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
Hello
Welcome
to
GeeksforGeeks
Example 2:
Python program to illustrate *args with a first extra argument.

def fun(arg1, *argv):


print("First argument :", arg1)
for arg in argv:
print("Argument *argv :", arg)

fun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output
First argument : Hello
Argument *argv : Welcome
Argument *argv : to
Argument *argv : GeeksforGeeks

Python **kwargs
The special syntax **kwargs in function definitions is used to pass a variable length
argument list. We use the name kwargs with the double star **.
 A keyword argument is where you provide a name to the variable as you pass it
into the function.
 It collects all the additional keyword arguments passed to the function and stores
them in a dictionary.
Example 1:

def fun(**kwargs):
for k, val in kwargs.items():
print("%s == %s" % (k, val))

# Driver code
90 | P a g e
fun(s1='Geeks', s2='for', s3='Geeks')

Output
s1 == Geeks
s2 == for
s3 == Geeks
For s1='Geeks', s1 is key and 'Geeks' is a value. In simple words, what we assign is
value and to whom we assign is key.
Example 2:

def fun(arg1, **kwargs):


for k, val in kwargs.items():
print("%s == %s" % (k, val))

# Driver code
fun("Hi", s1='Geeks', s2='for', s3='Geeks')

Output
s1 == Geeks
s2 == for
s3 == Geeks

Using both *args and **kwargs


We can use both *args and **kwargs in the same function to accept a mix of positional
and keyword arguments.
Example:

def fun(*args, **kwargs):


print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

fun(1, 2, 3, a=4, b=5)

Output
Positional arguments: (1, 2, 3)
Keyword arguments: {'a': 4, 'b': 5}
In this example, the fun can handle both positional and keyword arguments. The args
parameter collects positional arguments into a tuple, while the kwargs parameter
collects keyword arguments into a dictionary.
Why Python Uses 'Self' as Default Argument

91 | P a g e

In Python, when defining methods within a class, the first parameter is always self.
The parameter self is a convention not a keyword and it plays a key role in Python’s
object-oriented structure.
Example:

class Car:
def __init__(self,
brand, model):
self.brand = brand # Set instance attribute
self.model = model # Set instance attribute

def display(self):
return self.brand, self.model

# Create an instance of Car


car1 = Car("Toyota", "Corolla")

# Call the display_info method


print(car1.display()) # Output: This car is a Toyota Corolla

Output
('Toyota', 'Corolla')
Explanation:
 self in __init__: Used to assign values (brand and model) to the specific instance
(car1).
 self in display_info: Refers to the same car1 instance to access its attributes
(brand and model).
 Python automatically passes car1 as the first argument to display.
Let's understand the use of self as default argument in python in detail:
Why Python Uses 'Self' As Default Argument?
The main reason Python uses self as the default argument is to make object-oriented
programming explicit rather than implicit. By requiring the instance of the class to be
passed explicitly as the first parameter to every instance method, Python ensures
that the code is clear and unambiguous. This explicit approach makes it immediately
obvious that methods are operating on an instance of the class, which enhances
code readability and avoids confusion, especially in complex inheritance scenarios.
Why Not Implicit?
Unlike some other programming languages, Python requires self explicitly because:
 Clarity: Explicit is better than implicit (Python’s philosophy).
 Flexibility: You can name it anything, but self is a convention.

92 | P a g e
 Consistency: All instance methods in Python use this approach, making it
uniform.
Below, are the example of using 'Self' As A Default Argument in Python.
Example 1: Object Initialization & Method Invocation

class gfg:
def __init__(self, topic):
self._topic = topic # Rename the instance variable to avoid conflict

def topic(self):
print("Topic:", self._topic) # Access the renamed variable

# Creating an instance of gfg


ins = gfg("Python")

# Calling the topic method


ins.topic()

Output
Topic: Python
Explanation: In this example, 'self' is used to refer to the instance of the class, 'ins.'
Without the explicit use of 'self,' it would be unclear which instance the method is
referring to and the code might become ambiguous.
Example 2: Circle Class for Area Calculation Example
In this example, 'self' is crucial for accessing the 'r' attribute of the specific instance
'ins.' The use of 'self' ensures that the method operates on the attributes of the
correct instance.

class Circle:
def __init__(self, r):
self.r = r

def area(self):
a = 3.14 * self.r ** 2
return a

# Creating an instance of Circle


ins = Circle(5)

# Calling the area method


print("Area of the circle:", ins.area())

Output
Area of the circle: 78.5

93 | P a g e
Suggested Quiz
6 Questions
1. What is the purpose of the self keyword in Python classes?
 A
It refers to the class itself
 B
It is used to define private methods
 C
It refers to the current instance of the class
 D
It refers to the superclass
Explanation:- self represents the instance of the class. It's used to access instance variables and methods
from within the class.
2. What will be the output of the following code?
class MyClass:
def __init__(self, value):
self.value = value
def get(self):
return self.value
obj = MyClass(10)
print(obj.get())
 A
None
 B
Value
 C
10
 D
Error
Explanation:- The constructor initializes self.value with 10, and get() returns that value.
3. Why must self be the first parameter in instance methods?
 A
It's required by the Python interpreter to distinguish instance methods
 B
It's used for memory management
 C
It's a syntax convention, not a requirement
 D
It's only needed when inheriting from another class
Explanation:- The Python interpreter automatically passes the instance (self) as the first argument when
calling instance methods.
4. What will happen if self is omitted from an instance method definition?
class Test:
def show():
print("Hello")
94 | P a g e
t = Test()
t.show()
 A
Prints Hello
 B
Raises TypeError
 C
Prints nothing
 D
Prints None
Explanation:- The method show() doesn't accept self, so when the instance t is used to call it, Python still
passes self, causing a TypeError.
5. What will be the output of the following code?
class Sample:
def __init__(this, x):
this.x = x
def show(this):
print(this.x)
s = Sample(5)
s.show()
 A
this
 B
5
 C
Error
 D
None
Explanation:Although this is used instead of self, it's just a parameter name. The code works and prints 5.
6. What does self.__class__ refer to in an instance method?
 A
The class of the self instance
 B
The parent class
 C
The method name
 D
The memory location of self
Explanation: self.__class__ refers to the class to which the instance belongs, useful for introspection or
logging.
First Class functions in Python


95 | P a g e
First-class function is a concept where functions are treated as first-class citizens. By
treating functions as first-class citizens, Python allows you to write more abstract,
reusable, and modular code. This means that functions in such languages are treated
like any other variable. They can be passed as arguments to other functions,
returned as values from other functions, assigned to variables and stored in data
structures.
Characteristics of First-Class Functions
 Assigned to Variables: We can assign functions to variables.
 Passed as Arguments: We can pass functions as arguments to other functions.
 Returned from Functions: Functions can return other functions.
 Stored in Data Structures: Functions can be stored in data structures such as
lists, dictionaries, etc.

Assigning Functions to Variables


We can assign a function to a variable and use the variable to call the function.
Example:

def msg(name):
return f"Hello, {name}!"

# Assigning the function to a variable


f = msg

# Calling the function using the variable


print(f("Anurag"))

Output
Hello, Anurag!
Explanation:
 function greet is assigned to the variable f.
 f is then used to call the function, demonstrating that functions can be treated like
any other variable.
Passing Functions as Arguments
Functions can be passed as arguments to other functions, enabling higher-order
functions.
Example:

def msg(name):
return f"Hello, {name}!"

def fun1(fun2, name):


return fun2(name)

96 | P a g e
# Passing the greet function as an argument
print(fun1(msg, "Bob"))

Output
Hello, Bob!
Explanation:
 The fun1 function takes another function fun2 and a name as arguments.
 The msg function is passed to fun1, which then calls greet with the given name.
Returning Functions from Other Functions
A function can return another function, allowing for the creation of function factories.
Example:

def fun1(msg):
def fun2():
return f"Message: {msg}"
return fun2

# Getting the inner function


func = fun1("Hello, World!")
print(func())

Output
Message: Hello, World!
Explanation:
 The fun1 defines an fun2 and returns it.
 func stores the returned fun2, which can then be called later.
Storing Functions in Data Structures
Functions can be stored in data structures like lists or dictionaries.
Example:

def add(x, y):


return x + y

def subtract(x, y):


return x - y

# Storing functions in a dictionary


d={
"add": add,
"subtract": subtract
}

# Calling functions from the dictionary


print(d["add"](5, 3))
print(d["subtract"](5, 3))
97 | P a g e
Output
8
2
Explanation:
 Functions add and subtract are stored in a dictionary operations.
 Functions are accessed and called from the dictionary using their respective keys.

Suggested Quiz
8 Questions
1. Which of the following best describes a first-class function in programming languages?
 A
A function that can only be called from within its own scope.
 B
A function that can be assigned to variables, passed as arguments, and returned from
other functions like any other object.
 C
A function that can only be defined at the top level of a module.
 D
A function that can only be executed in a specific context.
2. In the context of first-class functions, what is a higher-order function?
 A
A function that can only return primitive data types.
 B
A function that can take other functions as arguments or return them as results.
 C
A function that is defined within another function but cannot be returned.
 D
A function that executes in a separate thread.

3. What will be the output of the following code?


def greet(name):
return f"Hello, {name}"
say_hello = greet
print(say_hello("Geek"))
 A
Hello, greet
 B
greet
 C
Hello, Geek
 D
TypeError
Explanation: Functions can be assigned to variables. Here, say_hello becomes another reference to
greet.
4. Which of the following is not a property of first-class functions?
98 | P a g e
 A
Functions can be stored in data structures
 B
Functions can be assigned to variables
 C
Functions can return other functions
 D
Functions can only return primitive types
Explanation: First-class functions can return any type, including other functions—not limited to primitives.
5. What will be the output of this code?
def outer():
def inner():
return "Inner function"
return inner
func = outer()
print(func())
 A
Inner function
 B
inner
 C
outer
 D
Error
Explanation: outer() returns the inner function, and func() calls it, returning its string.
6. Which of the following is NOT a characteristic of first-class functions?
 A
They can be assigned to variables.
 B
They can be passed as arguments to other functions.
 C
They can only be defined once in a program.
 D
They can be returned from other functions.
7. What is the output of the following code?
def make_multiplier(n):
def multiplier(x):
return x * n
return multiplier
double = make_multiplier(2)
print(double(5))
 A
7
 B
10
 C
25
99 | P a g e
 D
Error
Explanation: make_multiplier(2) returns a function that multiplies its argument by 2. So, double(5) returns
10.
8. How does Python treat functions with respect to variables?
 A
Functions are static objects
 B
Functions are constants and cannot be reassigned
 C
Functions are first-class citizens and can be stored, passed, and reassigned
 D
Functions must be declared global to be used
Explanation: Being first-class citizens means functions can be assigned, passed, and returned like other
objects.

Python Lambda Functions




Python Lambda Functions are anonymous functions means that the function is
without a name. As we already know the def keyword is used to define a normal
function in Python. Similarly, the lambda keyword is used to define an anonymous
function in Python.
In the example, we defined a lambda function(upper) to convert a string to its upper
case using upper().

s1 = 'GeeksforGeeks'

s2 = lambda func: func.upper()


print(s2(s1))

Output
GEEKSFORGEEKS
This code defines a lambda function named s2 that takes a string as its argument
and converts it to uppercase using the upper() method. It then applies this lambda
function to the string 'GeeksforGeeks' and prints the result.
Let's explore Lambda Function in detail:
Python Lambda Function Syntax
Syntax: lambda arguments : expression
 lambda: The keyword to define the function.

100 | P a g e
 arguments: A comma-separated list of input parameters (like in a regular
function).
 expression: A single expression that is evaluated and returned.
Let's see some of the practical uses of the Python lambda function.

lambda with Condition Checking


A lambda function can include conditions using if statements.
Example:

# Example: Check if a number is positive, negative, or zero


n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"

print(n(5))
print(n(-3))
print(n(0))

Output
Positive
Negative
Zero
Explanation:
 The lambda function takes x as input.
 It uses nested if-else statements to return "Positive," "Negative," or "Zero."
Difference Between lambda and def Keyword
lambda is concise but less powerful than def when handling complex logic. Let's take a
look at short comparison between the two:
Feature lambda Function Regular Function (def)

Definition Single expression with lambda. Multiple lines of code.

Name Anonymous (or named if assigned). Must have a name.

Statements Single expression only. Can include multiple statements.

Documentation Cannot have a docstring. Can include docstrings.

Reusability Best for short, temporary functions. Better for reusable and complex logic.

101 | P a g e
Example:

# Using lambda
sq = lambda x: x ** 2
print(sq(3))

# Using def
def sqdef(x):
return x ** 2
print(sqdef(3))

Output
9
9
As we can see in the above example, both the sq() function and sqdef() function
behave the same and as intended.
Lambda with List Comprehension
Combining lambda with list comprehensions enables us to apply transformations to
data in a concise way.
Example:

li = [lambda arg=x: arg * 10 for x in range(1, 5)]


for i in li:
print(i())

Output
10
20
30
40
Explanation:
 The lambda function squares each element.
 The list comprehension iterates through li and applies the lambda to each element.
 This is ideal for applying transformations to datasets in data preprocessing or
manipulation tasks.
Lambda with if-else
lambda functions can incorporate conditional logic directly, allowing us to handle
simple decision making within the function.
Example:

# Example: Check if a number is even or odd


check = lambda x: "Even" if x % 2 == 0 else "Odd"

102 | P a g e
print(check(4))
print(check(7))

Output
Even
Odd
Explanation:
 The lambda checks if a number is divisible by 2 (x % 2 == 0).
 Returns "Even" for true and "Odd" otherwise.
 This approach is useful for labeling or categorizing values based on simple
conditions.
Lambda with Multiple Statements
Lambda functions do not allow multiple statements, however, we can create two
lambda functions and then call the other lambda function as a parameter to the first
function.
Example:

# Example: Perform addition and multiplication in a single line


calc = lambda x, y: (x + y, x * y)

res = calc(3, 4)
print(res)

Output
(7, 12)
Explanation:
 The lambda function performs both addition and multiplication and returns a tuple
with both results.
 This is useful for scenarios where multiple calculations need to be performed and
returned together.
Lambda functions can be used along with built-in functions
like filter(), map() and reduce().
Using lambda with filter()
The filter() function in Python takes in a function and a list as arguments. This offers
an elegant way to filter out all the elements of a sequence "sequence", for which the
function returns True.
Example:

# Example: Filter even numbers from a list


n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even))

Output
103 | P a g e
[2, 4, 6]
Explanation:
 The lambda function checks if a number is even (x % 2 == 0).
 filter() applies this condition to each element in nums.
Using lambda with map()
The map() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and a new list is returned which contains all
the lambda-modified items returned by that function for each item.
Example:

# Example: Double each number in a list


a = [1, 2, 3, 4]
b = map(lambda x: x * 2, a)
print(list(b))

Output
[2, 4, 6, 8]
Explanation:
 The lambda function doubles each number.
 map() iterates through a and applies the transformation.
Using lambda with reduce()
The reduce() function in Python takes in a function and a list as an argument. The
function is called with a lambda function and an iterable and a new reduced result is
returned. This performs a repetitive operation over the pairs of the iterable. The
reduce() function belongs to the functools module.
Example:

from functools import reduce

# Example: Find the product of all numbers in a list


a = [1, 2, 3, 4]
b = reduce(lambda x, y: x * y, a)
print(b)

Output
24
Explanation:
 The lambda multiplies two numbers at a time.
 Reduce() applies this operation across the list.

Decorators in Python

104 | P a g e

In Python, decorators are a powerful and flexible way to modify or extend the
behavior of functions or methods, without changing their actual code.
 A decorator is essentially a function that takes another function as an argument
and returns a new function with enhanced functionality.
 Decorators are often used in scenarios such as logging, authentication and
memorization, allowing us to add additional functionality to existing functions or
methods in a clean, reusable way.
Python Decorators

Decorator Example:

# A simple decorator function


def decorator(func):

def wrapper():
print("Before calling the function.")
func()
print("After calling the function.")
return wrapper

# Applying the decorator to a function


@decorator

def greet():
print("Hello, World!")

greet()

Output
Before calling the function.
Hello, World!
After calling the function.
Explanation:
 decorator takes the greet function as an argument.
 It returns a new function (wrapper) that first prints a message, calls greet() and then
prints another message.
 The @decorator syntax is a shorthand for greet = decorator(greet).
Let's explore decorators in detail:
Syntax of Decorator Parameters

105 | P a g e
def decorator_name(func):
def wrapper(*args, **kwargs):
# Add functionality before the original function call
result = func(*args, **kwargs)
# Add functionality after the original function call
return result
return wrapper
@decorator_name
def function_to_decorate():
# Original function code
pass
Explanation of Parameters
1. decorator_name(func):
 decorator_name: This is the name of the decorator function.
 func: This parameter represents the function being decorated. When you use a
decorator, the decorated function is passed to this parameter.
2. wrapper(*args, **kwargs):
 wrapper: This is a nested function inside the decorator. It wraps the original
function, adding additional functionality.
 *args: This collects any positional arguments passed to the decorated function into
a tuple.
 **kwargs: This collects any keyword arguments passed to the decorated function
into a dictionary.
 The wrapper function allows the decorator to handle functions with any number and
types of arguments.
3. @decorator_name:
 This syntax applies the decorator to the function_to_decorate function. It is
equivalent to writing function_to_decorate =
decorator_name(function_to_decorate).
Higher-Order Functions
In Python, higher-order functions are functions that take one or more functions as
arguments, return a function as a result or do both. Essentially, a higher-order function
is a function that operates on other functions. This is a powerful concept in functional
programming and is a key component in understanding how decorators work.
Key Properties of Higher-Order Functions:
 Taking functions as arguments: A higher-order function can accept other
functions as parameters.
 Returning functions: A higher-order function can return a new function that can be
called later.
Example of a Higher-Order Function:

# A higher-order function that takes another function as an argument


def fun(f, x):
return f(x)

# A simple function to pass


106 | P a g e
def square(x):
return x * x

# Using apply_function to apply the square function


res = fun(square, 5)
print(res)

Output
25
In this example, first function fun is a higher-order function because it takes another
function f as an argument and applies it to the value x.
Role in Decorators:
Decorators in Python are a type of higher-order function because they take a function
as input, modify it, and return a new function that extends or changes its behavior.
Understanding higher-order functions is essential for working with decorators since
decorators are essentially functions that return other functions.
Functions as First-Class Objects
In Python, functions are first-class objects, meaning that they can be treated like
any other object, such as integers, strings, or lists. This gives functions a unique level
of flexibility and allows them to be passed around and manipulated in ways that are
not possible in many other programming languages.
What Does It Mean for Functions to Be First-Class Objects?
 Can be assigned to variables: Functions can be assigned to variables and used
just like any other value.
 Can be passed as arguments: Functions can be passed as arguments to other
functions.
 Can be returned from other functions: Functions can return other functions,
which is a key concept in decorators.
 Can be stored in data structures: Functions can be stored in lists, dictionaries, or
other data structures.

# Assigning a function to a variable


def greet(n):
return f"Hello, {n}!"

say_hi = greet # Assign the greet function to say_hi


print(say_hi("Alice")) # Output: Hello, Alice!

# Passing a function as an argument


def apply(f, v):
return f(v)

res = apply(say_hi, "Bob")


print(res) # Output: Hello, Bob!

# Returning a function from another function

107 | P a g e
def make_mult(f):
def mult(x):
return x * f
return mult

dbl = make_mult(2)
print(dbl(5)) # Output: 10

Output
Hello, Alice!
Hello, Bob!
10
Explanation:
 The code defines a greet function that returns a greeting message.
 The greet function is assigned to the say_hi variable, which is used to print a
greeting for "Alice".
 Another function, apply, takes a function and a value as arguments, applies the
function to the value, and returns the result.
 apply is demonstrated by passing say_hi and "Bob", printing a greeting for "Bob".
 The make_mult function creates a multiplier function based on a given factor.
Role of First-Class Functions in Decorators
 Decorators receive the function to be decorated as an argument. This allows the
decorator to modify or enhance the function's behavior.
 Decorators return a new function that wraps the original function. This new function
adds additional behavior before or after the original function is called.
 When a function is decorated, it is assigned to the variable name of the original
function. This means the original function is replaced by the decorated (wrapped)
function.
Types of Decorators
1. Function Decorators:
The most common type of decorator, which takes a function as input and returns a
new function. The example above demonstrates this type.

def simple_decorator(func):
def wrapper():
print("Before calling the function.")
func()
print("After calling the function.")
return wrapper

@simple_decorator
def greet():
print("Hello, World!")

greet()

108 | P a g e
Output
Before calling the function.
Hello, World!
After calling the function.
Explanation:
 simple_decorator(func): This decorator takes the function greet as an argument
(func) and returns a new function (wrapper) that adds some functionality before and
after calling the original function.
 @simple_decorator: This is the decorator syntax. It applies the simple_decorator
to the greet function.
 Calling greet(): When greet() is called, it doesn't just execute the original function
but first runs the added behavior from the wrapper function.
2. Method Decorators:
Used to decorate methods within a class. They often handle special cases, such as
the self argument for instance methods.

def method_decorator(func):
def wrapper(self, *args, **kwargs):
print("Before method execution")
res = func(self, *args, **kwargs)
print("After method execution")
return res
return wrapper

class MyClass:
@method_decorator
def say_hello(self):
print("Hello!")

obj = MyClass()
obj.say_hello()

Output
Before method execution
Hello!
After method execution
Explanation:
 method_decorator(func): The decorator takes the method (say_hello) as an
argument (func). It returns a wrapper function that adds behavior before and after
calling the original method.

109 | P a g e
 wrapper(self, *args, **kwargs): The wrapper must accept self because it is a
method of an instance. self is the instance of the class and *args and **kwargs
allow for other arguments to be passed if needed.
 @method_decorator: This applies the method_decorator to the say_hello method
of MyClass.
 Calling obj.say_hello(): The say_hello method is now wrapped with additional
behavior.
3. Class Decorators
Class decorators are used to modify or enhance the behavior of a class. Like function
decorators, class decorators are applied to the class definition. They work by taking
the class as an argument and returning a modified version of the class.
Example:

def fun(cls):
cls.class_name = cls.__name__
return cls

@fun
class Person:
pass

print(Person.class_name)

Output
Person
Explanation:
 add_class_name(cls): This decorator adds a new attribute, class_name, to the
class cls. The value of class_name is set to the name of the class (cls.__name__).
 @add_class_name: This applies the add_class_name decorator to the Person
class.
 Result: When the Person class is defined, the decorator automatically adds the
class_name attribute to it.
 print(Person.class_name): Accessing the class_name attribute that was added by
the decorator prints the name of the class, Person.
Common Built-in Decorators in Python
Python provides several built-in decorators that are commonly used in class
definitions. These decorators modify the behavior of methods and attributes in a class,
making it easier to manage and use them effectively. The most frequently used built-in
decorators are @staticmethod, @classmethod, and @property.
@staticmethod
The @staticmethod decorator is used to define a method that doesn't operate on an
instance of the class (i.e., it doesn't use self). Static methods are called on the class
itself, not on an instance of the class.
Example:

110 | P a g e
class MathOperations:
@staticmethod
def add(x, y):
return x + y

# Using the static method


res = MathOperations.add(5, 3)
print(res)

Output
8
Explanation:
 add is a static method defined with the @staticmethod decorator.
 It can be called directly on the class MathOperations without creating an instance.
@classmethod
The @classmethod decorator is used to define a method that operates on the class
itself (i.e., it uses cls). Class methods can access and modify class state that applies
across all instances of the class.
Example:

class Employee:
raise_amount = 1.05

def __init__(self, name, salary):


self.name = name
self.salary = salary

@classmethod
def set_raise_amount(cls, amount):
cls.raise_amount = amount

# Using the class method


Employee.set_raise_amount(1.10)
print(Employee.raise_amount)

Output
1.1
Explanation:
 set_raise_amount is a class method defined with the @classmethod decorator.
 It can modify the class variable raise_amount for the class Employee and all its
instances.
@property
The @property decorator is used to define a method as a property, which allows you
to access it like an attribute. This is useful for encapsulating the implementation of a
method while still providing a simple interface.

111 | P a g e
Example:

class Circle:
def __init__(self, radius):
self._radius = radius

@property
def radius(self):
return self._radius

@radius.setter
def radius(self, value):
if value >= 0:
self._radius = value
else:
raise ValueError("Radius cannot be negative")

@property
def area(self):
return 3.14159 * (self._radius ** 2)

# Using the property


c = Circle(5)
print(c.radius)
print(c.area)
c.radius = 10
print(c.area)

Output
5
78.53975
314.159
Explanation:
 radius and area are properties defined with the @property decorator.
 The radius property also has a setter method to allow modification with validation.
 These properties provide a way to access and modify private attributes while
maintaining encapsulation.
Chaining Decorators
In simpler terms chaining decorators means decorating a function with multiple
decorators.
Example:

# code for testing decorator chaining


def decor1(func):
def inner():
x = func()
return x * x
112 | P a g e
return inner

def decor(func):
def inner():
x = func()
return 2 * x
return inner

@decor1
@decor
def num():
return 10

@decor
@decor1
def num2():
return 10

print(num())
print(num2())

Output
400
200

Python map() function



The map() function is used to apply a given function to every item of an iterable,
such as a list or tuple, and returns a map object (which is an iterator).
Let's start with a simple example of using map() to convert a list of strings into a
list of integers.

s = ['1', '2', '3', '4']


res = map(int, s)
print(list(res))

Output
[1, 2, 3, 4]

113 | P a g e
Explanation: Here, we used the built-in int function to convert each string in the list
s into an integer. The map() function takes care of applying int() to every element
Table of Content
 Converting map object to a list
 map() with lambda
 Using map() with multiple iterables
 Examples of map() function
o Converting to uppercase
o Extracting first character from strings
o Removing whitespaces from strings
o Calculate fahrenheit from celsius
Syntax of the map() function
The syntax for the map() function is as follows:
map(function, iterable)
Parameter:
 function: The function we want to apply to every element of the iterable.
 iterable: The iterable whose elements we want to process.
Note: We can also pass multiple iterables if our function accepts multiple arguments.
Converting map object to a list
By default, the map() function returns a map object, which is an iterator. In many
cases, we will need to convert this iterator to a list to work with the results directly.
Example: Let's see how to double each elements of the given list.

a = [1, 2, 3, 4]

# Using custom function in "function" parameter


# This function is simply doubles the provided number
def double(val):
return val*2

res= list(map(double, a))


print(res)

Output
[2, 4, 6, 8]
Explanation:
 The map() function returned an iterator, which we then converted into a list
using list(). This is a common practice when working with map()
 We used a custom function to double each value in the list a. The result was
mapped and converted into a list for easy display.
map() with lambda
We can use a lambda function instead of a custom function with map() to make the
code shorter and easier. Let's see how to improve the above code for better
readability.
114 | P a g e
a = [1, 2, 3, 4]

# Using lambda function in "function" parameter


# to double each number in the list
res = list(map(lambda x: x * 2, a))
print(res)

Output
[2, 4, 6, 8]
Explanation: We used lambda x: x * 2 to double each value in the list a. The result
was mapped and converted into a list for easy display.
Using map() with multiple iterables
We can use map() with multiple iterables if the function we are applying takes more
than one argument.
Example: In this example, map() takes two iterables (a and b) and applies
the lambda function to add corresponding elements from both lists.

a = [1, 2, 3]
b = [4, 5, 6]
res = map(lambda x, y: x + y, a, b)
print(list(res))

Output
[5, 7, 9]

Examples of map() function


Converting to uppercase
This example shows how we can use map() to convert a list of strings to uppercase.

fruits = ['apple', 'banana', 'cherry']


res = map(str.upper, fruits)
print(list(res))

Output
['APPLE', 'BANANA', 'CHERRY']
Explanation: The str.upper method is applied to each element in the list fruits
using map(). The result is a list of uppercase versions of each fruit name.
Extracting first character from strings
In this example, we use map() to extract the first character from each string in a list.

words = ['apple', 'banana', 'cherry']


res = map(lambda s: s[0], words)
print(list(res))

115 | P a g e
Output
['a', 'b', 'c']
Explanation: The lambda function s: s[0] extracts the first character from each
string in the list words. map() applies this lambda function to every element, resulting
in a list of the first characters of each word.
Removing whitespaces from strings
In this example, We can use map() to remove leading and trailing whitespaces from
each string in a list.

s = [' hello ', ' world ', ' python ']


res = map(str.strip, s)
print(list(res))

Output
['hello', 'world', 'python']
Explanation: The str.strip method removes leading and trailing whitespaces from
each string in the list strings. The map() function applies str.strip to each element
and returning a list of trimmed strings.
Calculate fahrenheit from celsius
In this example, we use map() to convert a list of temperatures from Celsius to
Fahrenheit.

celsius = [0, 20, 37, 100]


fahrenheit = map(lambda c: (c * 9/5) + 32, celsius)
print(list(fahrenheit))

Output
[32.0, 68.0, 98.6, 212.0]
Explanation: The lambda function c: (c * 9/5) + 32 converts each Celsius
temperature to Fahrenheit using the standard formula. The map() function applies
this transformation to all items in the list celsius.

reduce() in Python


The reduce(fun,seq) function is used to apply a particular function passed in


its argument to all of the list elements mentioned in the sequence passed
along. This function is defined in "functools" module.

116 | P a g e
Basic Example:
Let’s start with a simple example where we sum up all numbers in a list.

from functools import reduce

# Function to add two numbers


def add(x, y):
return x + y

a = [1, 2, 3, 4, 5]
res = reduce(add, a)

print(res) # Output: 15

Output
15
Explanation:
 The reduce() function applies add() cumulatively to the elements in numbers. First,
1 + 2 = 3. Then, 3 + 3 = 6. And so on, until all numbers are processed.
 The final result is 15.
Let's understand reduce function in detail:
Syntax of reduce()
functools.reduce(function, iterable[, initializer])
 function: A function that takes two arguments and performs an operation on them.
 iterable: An iterable whose elements are processed by the function.
 initializer (optional): A starting value for the operation. If provided, it is placed
before the first element in the iterable.
The reduce() function is part of the functools module, so you need to import it before
use.
Using reduce() with lambda
When paired with a lambda function, reduce() becomes a concise and powerful tool
for aggregation tasks like summing, multiplying or finding the maximum value.

from functools import reduce

# Summing numbers with reduce and lambda


a = [1, 2, 3, 4, 5]
res = reduce(lambda x, y: x + y, a)

print(res)

Output
15
Explanation:

117 | P a g e
 The lambda function takes two arguments (x and y) and returns their sum.
 reduce() starts by applying the function to the first two elements: 1 + 2 = 3.
 The result (3) is then used with the next element: 3 + 3 = 6, and so on.
 The process continues until all elements are processed, yielding 15.
Using reduce() with operator functions
reduce() can also be combined with operator functions to achieve the similar
functionality as with lambda functions and makes the code more readable.

import functools

# importing operator for operator functions


import operator

# initializing list
a = [1, 3, 5, 6, 2]

# using reduce with add to compute sum of list


print(functools.reduce(operator.add, a))

# using reduce with mul to compute product


print(functools.reduce(operator.mul, a))

# using reduce with add to concatenate string


print(functools.reduce(operator.add, ["geeks", "for", "geeks"]))

Output
17
180
geeksforgeeks
Explanation:
 operator.add and operator.mul function are predefined operators.
 reduce() applies the add function cumulatively to elements in the list.
 The operation works similarly to the lambda example but the code is cleaner and
more readable.
Difference Between reduce() and accumulate()
The accumulate() function from the itertools module also performs cumulative
operations, but it returns an iterator containing intermediate results, unlike reduce(),
which returns a single final value.
Example with accumulate:

from itertools import accumulate


from operator import add

# Cumulative sum with accumulate


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

118 | P a g e
res = accumulate(a, add)

print(list(res))

Output
[1, 3, 6, 10, 15]

Key Differences
Feature reduce() accumulate()

Return Intermediate results (e.g., [1, 3, 6,


A single final value (e.g., 15).
Value 10, 15]).

Output
Returns a single value. Returns an iterator.
Type

Useful when only the final result is


Use Case Useful when tracking cumulative steps.
needed.

Import From functools. From itertools.

Suggested Quiz
6 Questions
1. What is the primary purpose of the reduce() function in Python?
 A
To reduce the size of a list
 B
To apply a function to items in a list and return a single cumulative result
 C
To remove duplicates from a list
 D
To filter elements from a list based on a condition
Explanation:- reduce() repeatedly applies a function to the items of an iterable to reduce it to a single
value.
2. Which module must be imported to use reduce() in Python 3?
 A
math
 B
operator
 C
functools

119 | P a g e
 D
itertools
3. What is the output of the following code?
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums)
print(result)
 A
10
 B
24
 C
1234
 D
Error
Explanation: reduce() applies the lambda cumulatively: (((1+2)+3)+4) = 10.
4. How does the reduce function differ from the map function in Python?
 A
Reduce returns a single cumulative value, while map returns an iterable of results
 B
Reduce can only work with numeric types, while map can work with any type
 C
Reduce applies the function to each element independently, while map combines them
 D
Reduce requires an initializer, while map does not
5. What will this code return?
from functools import reduce
nums = [2, 3, 4]
result = reduce(lambda x, y: x * y, nums)
print(result)
 A
24
 B
9
 C
Error
 D
6
Explanation: Multiplying cumulatively: 2 * 3 = 6, then 6 * 4 = 24.
6. Which of the following is not true about reduce()?
 A
It can only be used with numeric data types
 B
It stops execution if the iterable is empty and no initializer is provided
 C
It returns a single value after processing all elements
 D
It accepts an optional initializer argument

120 | P a g e
Explanation: reduce() can be used with any data types, such as strings, as long as the function supports
them.

filter() in python


The filter() method filters the given sequence with the help of a function that tests
each element in the sequence to be true or not. Let's see a simple example of filter()
function in python:
Example Usage of filter()

# Function to check if a number is even


def even(n):
return n % 2 == 0

a = [1, 2, 3, 4, 5, 6]
b = filter(even, a)

# Convert filter object to a list


print(list(b))

Output
[2, 4, 6]
Explanation:
 Function: even function checks if a number is divisible by 2.
 Filter: The filter() applies this function to each item in numbers.
 Result: A new iterable containing only even numbers is returned.
Let's explore filter() in detail:
Python filter() Syntax
The filter() method in Python has the following syntax:
Syntax: filter(function, sequence)
 function: A function that defines the condition to filter the elements. This function
should return True for items you want to keep and False for those you want to
exclude.
 iterable: The iterable you want to filter (e.g., list, tuple, set).
The result is a filter object, which can be converted into a list, tuple or another iterable
type.
Let us see a few examples of the filter() function in Python.
Using filter() with lambda

121 | P a g e
For concise conditions, we can use a lambda function instead of defining a named
function.

a = [1, 2, 3, 4, 5, 6]
b = filter(lambda x: x % 2 == 0, a)

print(list(b))

Output
[2, 4, 6]
Here, the lambda function replaces even and directly defines the condition x % 2 == 0
inline.
Combining filter() with Other Functions
We can combine filter() with other Python functions like map() or use it in a pipeline to
process data efficiently.
Example: Filtering and Transforming Data

a = [1, 2, 3, 4, 5, 6]

# First, filter even numbers


b = filter(lambda x: x % 2 == 0, a)

# Then, double the filtered numbers


c = map(lambda x: x * 2, b)

print(list(c))

Output
[4, 8, 12]
Explanation:
 The filter() function extracts even numbers from numbers.
 The map() function doubles each filtered number.
 The combination simplifies complex data pipelines.

Python Inner Functions




In Python, a function inside another function is called an inner function or nested


function. Inner functions help in organizing code, improving readability and
maintaining encapsulation. They can access variables from the outer function, making
them useful for implementing closures and function decorators.
Example:
122 | P a g e
def fun1(msg): # outer function

deffun2(): # inner function


print(msg)
fun2()

fun1("Hello")

Output
Hello
Explanation: Here, fun2() is definedinside fun1() and it accesses the
variable msg from the enclosing scope.
Why Use Inner functions?
Inner functions provide several advantages:
 Encapsulation: They help hide the inner logic from external access.
 Code Organization: They make the code cleaner by grouping related functionality.
 Access to Enclosing Scope: Inner functions can access variables of the outer
function.
 Closures: They allow functions to retain the state of their enclosing function even
after execution.
Scope of variables in inner functions
Inner functions can access variables from their enclosing (outer) function, but
modifying them requires special handling. This follows Python’s LEGB rule (Local,
Enclosing, Global, Built-in) for variable scope.
Example 1 : Local Variable Access

deffun1(): # outer function


msg = "Geeks for geeks"

def fun2(): # inner function


print(msg) # accessing outer function's variable

fun2()
fun1()

Output
Geeks for geeks
Explanation: fun1() defines a local variable msg and an inner function fun2(), which
prints msg. Due to lexical scoping, fun2() accesses msg from fun1().
Calling fun1() invokes fun2(), printing the message.
Example 2: Modifying variables using nonlocal

def fun1(): # outer function


123 | P a g e
a = 45

def fun2(): # inner function


nonlocal a # allows modification of `a` from fun1
a=54
print(a)

fun2()
print(a)

fun1()

Output
54
54
Explanation: nonlocal keyword allows fun2() to modify the
variable a from fun1(). Without nonlocal, a inside fun2() would be treated as a new
local variable instead of modifying the one in fun1().
Example 3 : closure in inner function

def fun1(a): # outer function

def fun2(): # inner function


print(a)
return fun2 # returning function without parentheses

closure_func = fun1("Hello, Closure!")


closure_func() # inner function remembers 'a'

Output
Hello, Closure!
Explanation: Even after fun1() completes execution, the returned fun2() function
retains access to a, demonstrating a closure.
Real - World Applications of inner functions
Inner functions are useful in real-world scenarios for better code organization,
encapsulation and reusability. Below are some practical applications:
Example1 : Encapsulation of helper functions

def process_data(data):
# removes extra spaces from a list

def clean_data():
return [item.strip() for item in data] # Strip spaces

return clean_data() # return cleaned list

124 | P a g e
print(process_data([" Python ", " Inner Function "]))

Output
['Python', 'Inner Function']
Explanation: process_data(data) removes leading and trailing whitespace from each
string in the input list. It defines a nested function, clean_data(), which trims spaces
using .strip() and returns the cleaned list.
Example 2 : Function wrapper and logging
import logging

logging.basicConfig(level=logging.INFO) # configure logging

def logger(func):
# logs function execution details

def wrapper(*args, **kwargs):


logging.info(f"Executing {func.__name__} with {args}, {kwargs}") # log
function call
return func(*args, **kwargs) # call original function
return wrapper

@logger
def add(a, b):
return a + b # return sum

print(add(3, 4))
Output:
INFO:root:Executing add with arguments (3, 4), {}
7
Explanation: logger function, *args captures positional arguments,
and **kwargs captures keyword arguments, allowing the wrapper to handle any
function signature.
Best Practices for using inner functions
Inner functions are powerful but should be used wisely to maintain code readability,
efficiency and maintainability. Below are some best practices:
 Use inner functions only when necessary: Avoid excessive nesting, as it can
reduce readability.
 Use closures wisely: Ensure that captured variables are managed properly to
prevent unintended side effects.
 Prefer nonlocal over global variables: If modifying outer function variables, use
nonlocal instead of global.
 Use inner functions in decorators: This is a common and effective use case.

Suggested Quiz
6 Questions
1. What is an inner function in Python?
125 | P a g e
 A
A function that is called from within a class
 B
A function defined inside another function
 C
A function that inherits from another function
 D
A function used only with classes
Explanation: An inner function is defined within another function and can access the outer function’s
variables.
2. When defining an inner function, what is the scope of variables from the outer function?
 A
They are accessible only if passed as parameters.
 B
They are accessible and can be modified directly.
 C
They are not accessible at all.
 D
They are accessible but cannot be modified without special handling.
3. What will the following code output?
def outer():
def inner():
return "Hello from inner"
return inner()
print(outer())
 A
"Hello from inner"
 B
inner()
 C
Error
 D
None
Explanation: The outer() function defines inner() and immediately calls it, returning its result.
4. What is the scope of a variable declared inside an inner function?
 A
Global scope
 B
Local to the outer function
 C
Local to the inner function
 D
Class-level scope
Explanation: A variable inside an inner function is local to that function and not accessible outside it
unless returned.
5. Which of the following best describes the LEGB rule in Python?
 A
It describes the order of function execution.
126 | P a g e
 B
It outlines the scope resolution order Local, Enclosing, Global, Built-in.
 C
It defines the rules for variable naming.
 D
It specifies the data types available in Python.
6. Can an inner function access variables from the enclosing function?
 A
No, Python does not support this
 B
Only if declared global
 C
Yes, via lexical scoping
 D
Only if passed explicitly as arguments
Explanation: Python supports lexical scoping, allowing inner functions to access variables from the outer
function.

Python Functions
Question 1
What will be the output of the following code :
print(type(type(int)))

 A
type \'int\'
 B
type \'type\'
 C
Error
 D
0
Explanation
The type() function returns the class of the argument the object belongs to. Thus, type(int)
returns which is of the type ‘type’ object.
Question 2
What is the output of the following code :
li = ['a', 'b', 'c', 'd']
print("".join(li))
 A
Error
 B
None
 C
abcd
 D
[‘a’,’b’,’c’,’d’]
Explanation
“” depicts a null string and the join function combines the elements of the list into a string.
Question 3

127 | P a g e
What is the output of the following segment :
print(chr(ord('A')))
 A
A
 B
B
 C
a
 D
Error
Explanation
ord() function converts a character into its ASCII notation and chr() converts the ASCII to
character.
Question 4
What is the output of the following program :
y=8
z = lambda x : x * y
print(z(6))
 A
48
 B
14
 C
64
 D
None of the above

Explanation
Lambda multiplies input by outer scope variable y = 8, so z(6) is 6*8 = 48.
Question 5
What is called when a function is defined inside a class?
 A
Module
 B
Class
 C
Another Function
 D
Method
Explanation
When a function is defined inside a class then it is called Method. The method is accessible to
data that is contained within the class.
Question 6
Which of the following is the use of id() function in python?
 A

128 | P a g e
Id returns the identity of the object
 B
Every object doesn’t have a unique id
 C
All of the mentioned
 D
None of the mentioned

Explanation
Each object in Python has a unique id. The id() function returns the object’s id.
Question 7
What is the output of the following program :
def func(a, b=[]):
b.append(a)
return b

print(func(1))
print(func(2))
 A
[1]
[2]
 B
[1]
[1, 2]
 C
[1]
[1]
 D
None of the above
Discuss it

Explanation
In Python, default mutable arguments like lists retain their state across function calls. The list b
is initialized only once when the function is defined, not each time it's called. Therefore:
 func(1) appends 1 to the default list b, resulting in [1].
 func(2) appends 2 to the same list b, which already contains [1], resulting in [1, 2].
This behavior can lead to unexpected results if not carefully managed. To avoid this, it's
common practice to use None as the default value and initialize the list inside the function:
def func(a, b=None):
b.append(a)
return b

print(func(1))
print(func(2))

129 | P a g e
Question 8
Suppose li is [3, 4, 5, 20, 5, 25, 1, 3], what is li after li.pop(1)?
 A
[3, 4, 5, 20, 5, 25, 1, 3]
 B
[1, 3, 3, 4, 5, 5, 20, 25]
 C
[3, 5, 20, 5, 25, 1, 3]
 D
[1, 3, 4, 5, 20, 5, 25]
Explanation
pop(i) removes the ith index element from the list
Question 9
time.time() returns ________
 A
The current time as a string formatted as "HH:MM:SS".
 B
The current time in milliseconds since January 1, 1970 UTC (Unix epoch).
 C
The current time in seconds (including fractions) since January 1, 1970 UTC (Unix epoch).
 D
The system’s local time in seconds since midnight.

Explanation
time.time() returns the number of seconds as a floating-point number that have elapsed since
the Unix epoch (January 1, 1970, UTC). This value includes fractional seconds to provide
precision. It does not return milliseconds or a formatted string, nor does it return local time
since midnight.
Question 10
What will be the output of the following code?
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner

closure = outer()
print(closure())
print(closure())

 A
15
20

 B

130 | P a g e
15
15
 C
10
15
 D
5
5

Explanation
The nonlocal keyword allows modification of x inside the inner function, which maintains state
between function calls.

3. Python Data Structures

Python offers versatile collections of data types, including lists, string, tuples, sets,
dictionaries and arrays. In this section, we will learn about each data types in detail.
 Strings
 List
 Quiz: List, String
 Tuples
 Dictionary
 Quiz: Tuples, Dictionary
 Sets
 Arrays
 List Comprehension
 Quiz: Sets, Arrays, List Comprehension
Python's collections module offers essential data structures, including the following:
 Counters
 Heapq
 Deque
 OrderedDict
 Defaultdict
 Quiz: Counters, Heapq, Deque, OrderedDict
To learn data structure and algorithm with python in detail, you can refer to our DSA
with Python Tutorial.

Definition 3.

Python String
131 | P a g e


A string is a sequence of characters. Python treats anything inside quotes as a string.


This includes letters, numbers, and symbols. Python has no character data type so
single character is a string of length 1.

s = "GfG"

print(s[1])# access 2nd char


s1 = s + s[0] # update
print(s1) # print

Output
f
GfGG
In this example, s holds the value "GfG" and is defined as a string.
Creating a String
Strings can be created using either single (') or double (") quotes.

s1 = 'GfG'
s2 = "GfG"
print(s1)
print(s2)

Output
GfG
GfG

Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (''' or """).

s = """I am Learning
Python String on GeeksforGeeks"""
print(s)

s = '''I'm a
Geek'''
print(s)

Output
I am Learning

132 | P a g e
Python String on GeeksforGeeks
I'm a
Geek

Accessing characters in Python String


Strings in Python are sequences of characters, so we can access individual characters
using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to
retrieve specific characters from the string.

Python String syntax indexing

s = "GeeksforGeeks"

# Accesses first character: 'G'


print(s[0])

# Accesses 5th character: 's'


print(s[4])

Output
G
s
Note: Accessing an index out of range will cause an IndexError. Only integers are
allowed as indices and using a float or other types will result in a TypeError.
Access string with Negative Indexing
Python allows negative address references to access characters from back of the
String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.

s = "GeeksforGeeks"

# Accesses 3rd character: 'k'


print(s[-10])

133 | P a g e
# Accesses 5th character from end: 'G'
print(s[-5])

Output
k
G

String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes.
The syntax for slicing is string[start:end], where start starting index and end is
stopping index (excluded).

s = "GeeksforGeeks"

# Retrieves characters from index 1 to 3: 'eek'


print(s[1:4])

# Retrieves characters from beginning to index 2: 'Gee'


print(s[:3])

# Retrieves characters from index 3 to the end: 'ksforGeeks'


print(s[3:])

# Reverse a string
print(s[::-1])

Output
eek
Gee
ksforGeeks
skeeGrofskeeG

String Immutability
Strings in Python are immutable. This means that they cannot be changed after
they are created. If we need to manipulate strings then we can use methods
like concatenation, slicing, or formatting to create new strings based on the original.

s = "geeksforGeeks"

# Trying to change the first character raises an error


# s[0] = 'I' # Uncommenting this line will cause a TypeError

# Instead, create a new string


s = "G" + s[1:]
print(s)

134 | P a g e
Output
GeeksforGeeks

Deleting a String
In Python, it is not possible to delete individual characters from a string since strings
are immutable. However, we can delete an entire string variable using
the del keyword.
s = "GfG"

# Deletes entire string


del s
Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.
Updating a String
To update a part of a string we need to create a new string since strings are
immutable.

s = "hello geeks"

# Updating by creating a new string


s1 = "H" + s[1:]

# replacnig "geeks" with "GeeksforGeeks"


s2 = s.replace("geeks", "GeeksforGeeks")
print(s1)
print(s2)

Output
Hello geeks
hello GeeksforGeeks
Explanation:
 For s1, The original string s is sliced from index 1 to end of string and then
concatenate "H" to create a new string s1.
 For s2, we can created a new string s2 and used replace() method to replace
'geeks' with 'GeeksforGeeks'.
Common String Methods
Python provides a various built-in methods to manipulate strings. Below are some of
the most useful methods.
len(): The len() function returns the total number of characters in a string.

s = "GeeksforGeeks"
print(len(s))

# output: 13

135 | P a g e
Output
13
upper() and lower(): upper() method converts all characters to
uppercase. lower() method converts all characters to lowercase.

s = "Hello World"

print(s.upper()) # output: HELLO WORLD

print(s.lower()) # output: hello world

Output
HELLO WORLD
hello world
strip() and replace(): strip() removes leading and trailing whitespace from the string
and replace(old, new) replaces all occurrences of a specified substring with another.

s = " Gfg "

# Removes spaces from both ends


print(s.strip())

s = "Python is fun"

# Replaces 'fun' with 'awesome'


print(s.replace("fun", "awesome"))

Output
Gfg
Python is awesome
To learn more about string methods, please refer to Python String Methods.
Concatenating and Repeating Strings
We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.

s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3)

Output
Hello World

136 | P a g e
We can repeat a string multiple times using * operator.

s = "Hello "
print(s * 3)

Output
Hello Hello Hello

Formatting Strings
Python provides several ways to include variables inside strings.
Using f-strings
The simplest and most preferred way to format strings is by using f-strings.

name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")

Output
Name: Alice, Age: 22

Using format()
Another way to format strings is by using format() method.

s = "My name is {} and I am {} years old.".format("Alice", 22)


print(s)

Output
My name is Alice and I am 22 years old.

Using in for String Membership Testing


The in keyword checks if a particular substring is present in a string.

s = "GeeksforGeeks"
print("Geeks" in s)
print("GfG" in s)

Output
True
False

Python String Quiz


This quiz focuses on testing and improving your understanding of Python strings, one of the most
widely used data types in programming.
Question 1. Which of the following is true about lists in Python?
 A

137 | P a g e
Lists are dynamic sized arrays
 B
Lists store references at items contiguous locations
 C
A list can contain elements of different types.
 D
All of the above
Question 2. What are strings in Python?

 A
Arrays of bytes representing Unicode characters
 B
Arrays of integers representing characters
 C
Single characters only
 D
Arrays of floats representing characters
Question 3. What does the string method .join() do in Python?
 A
Splits a string into a list
 B
Concatenates a list of strings into one string
 C
Reverses a string
 D
Returns the index of a substring in the string
Explanation- The join() method in Python is a built-in string method that is used to concatenate
(join) a sequence of strings into a single string.
Question 4. Which method can be used to handle strings with both single and double quotes
simultaneously in Python?

 A
Using triple quotes
 B
Using backslash ()
 C
Using parentheses
 D
Using single quotes only
ExplanationTriple quotes allow you to use both single and double quotes inside the string
without escaping them.
Example:

str = '''She said, "I'm learning Python."'''

print str;
# Output: She said, "I'm learning Python."

Question 5. How can you print a string without resolving escape sequences in Python?

 A

138 | P a g e
By using the repr() function
 B
By using the eval() function
 C
By using the str() function
 D
By using the format() function
Explanation- In python repr() function ensure that the escape sequences are displayed as part
of the string rather than being processed.
Example:
string = "Hello\nWorld\t!"

print(repr(string)) # Output: 'Hello\nWorld\t!'

Question 6. What is the primary reason that updating or deleting characters from a string in
Python is not allowed?
 A
Strings are mutable data types
 B
Python strings are immutable data types
 C
Python doesn't support character-level operations on strings
 D
Python string operations are not efficient
Explanation- Python strings are immutable. This means that once a string is created, it
cannot be modified. Any operation that seems to modify a string will instead create a new
string.
Example :

s = "Hello"
s[0] = "h" # This will raise an error.

Question 7. What is the purpose of the find() function in Python strings?


 A
It returns the position of the last occurrence of a substring within a string.
 B
It returns true if the string begins with a specified prefix.
 C
It returns the position of the first occurrence of a substring within a string.
 D
It returns true if all the letters in the string are lowercased.

Explanation-In Python, the find() method is used to search for a substring within a string. It
returns the index of the first occurrence of the substring. If the substring is not found, it returns -
1.
Example :

139 | P a g e
text = "Hello, World!"
index = text.find("World")
print(index) # Output: 7

Question 8. What does the startswith() function in Python do?


 A
It returns true if all the letters in the string are uppercased.
 B
It returns true if the string starts with a specified prefix.
 C
It returns true if the string ends with a specified suffix.
 D
It returns true if all the letters in the string are lowercased
Explanation- In Python, the startswith() method is used to check whether a string starts with a
specified prefix. It returns True if the string starts with the given prefix, otherwise, it
returns False.
Example:

text = "Hello, World!"


result = text.startswith("Hello")
print(result) # Output: True

Question 9. What does the title() method do in Python strings?

 A
It converts the first letter of every word to uppercase and others to lowercase.
 B
It swaps the cases of all letters in the string.
 C
It converts all letters to uppercase.
 D
It converts all letters to lowercase.
Explanation- The title() method in Python converts the first character of each word in a string to
uppercase and the rest of the characters to lowercase.
Example:

text = "hello world"


result = text.title()
print(result) # Output: "Hello World"

Question 10. What is the time complexity of the find() function in Python?

 A
O(log n)
 B
O(n^2)
 C
O(n)
 D
O(1)
140 | P a g e
Explanation- For a string of length n and a substring of length m, the find() method compares
each possible starting position in the string where the substring could fit, and checks for a
match. If no match is found, it will continue until the end of the string.
Therefore the time complexity for find() in O(n) where n is the length of the string.

Question 11. What does the count() function in Python do?


 A
It counts the total number of characters in a string.
 B
It counts the occurrences of a specified substring within a string.
 C
It returns true if all characters in the string are alphabets.
 D
It returns true if all characters in the string are numbers.
Explanation- In Python, the count() method counts the occurrences of a substring within a
string. It returns the number of non-overlapping occurrences of the specified substring.
Example:

text = "hello world, hello Python"


result = text.count("hello")
print(result) # Output: 2

Question 12. What does the isalpha() function in Python return?

 A
True if all characters in the string are alphabets, else False.
 B
True if all characters in the string are numbers, else False.

 C
True if all characters in the string are alphanumeric, else False.
 D
True if all characters in the string are spaces, else False.
Explanation- In Python, the isalpha() method is used to check whether all characters in a string
are alphabetic (i.e., they are letters).
The method returns True if all characters in the string are alphabetic and the string is non-
empty, otherwise, it returns False.
Example:

text = "Hello"
result = text.isalpha()
print(result) # Output: True

Question 13. What does the strip() method do in Python?

 A
Deletes all the leading characters mentioned in its argument.
 B

141 | P a g e
Deletes all the trailing characters mentioned in its argument.
 C
Deletes all the leading and trailing characters mentioned in its argument.
 D
Splits the string based on the characters mentioned in its argument.
Explanation- The strip() method in Python is used to remove leading and trailing
whitespaces (spaces, tabs, newlines, etc.) from a string. It can also remove specific characters
if provided as an argument.
Example:

text = " Hello, World! "


result = text.strip()
print(result) # Output: "Hello, World!"

text = "///Hello, World!///"


result = text.strip("/")
print(result) # Output: "Hello, World!"

Question 14. Which method is best suited to replace all tab characters with whitespace using the
given tab size?
 A
strip()
 B
expandtabs()
 C
replace()
 D
maketrans()
Question 15. Which method is used to create a Regex object in Python?
 A
regex.compile()
 B
re.create()
 C
re.compile()
 D
regex.create()
Explanation- re.compile() function compiles a regular expression pattern into a Regex object,
which can be used for matching and searching efficiently.
Question 16. What is the purpose of the translate() function in Python?
 A
It is used to map the contents of string 1 with string 2 with respective indices to be translated
later.
 B
It is used to swap the string elements mapped with the help of maketrans().
 C
It is used to replace the substring with a new substring in the string.
 D
It is used to replace all tab characters with whitespace using the given tab size.

142 | P a g e
Explanation- translate() function modifies a string based on a translation table created using
maketrans().

Python Lists


In Python, a list is a built-in dynamic sized array (automatically grows and shrinks).
We can store all types of items (including another list) in a list. A list may contain
mixed type of items, this is possible because a list mainly stores references at
contiguous locations and actual items maybe stored at different locations.
 List can contain duplicate items.
 List in Python are Mutable. Hence, we can modify, replace or delete the items.
 List are ordered. It maintain the order of elements based on how they are added.
 Accessing items in List can be done directly using their position (index), starting
from 0.
Example :

# Creating a Python list with different data types


a = [10, 20, "GfG", 40, True]
print(a)

# Accessing elements using indexing


print(a[0]) # 10
print(a[1]) # 20
print(a[2]) # "GfG"
print(a[3]) # 40
print(a[4]) # True

# Checking types of elements


print(type(a[2])) # str
print(type(a[4])) # bool
Explanation:
 The list contains a mix of integers (10, 20, 40), a string ("GfG") and a boolean
(True).
 The list is printed and individual elements are accessed using their indexes
(starting from 0).
 type(a[2]) confirms "GfG" is a str.
 type(a[4]) confirms True is a bool.

143 | P a g e
Python List
Note: Lists Store References, Not Values
Each element in a list is not stored directly inside the list structure. Instead, the list
stores references (pointers) to the actual objects in memory. Example (from the
image representation).
 The list a itself is a container with references (addresses) to the actual values.
 Python internally creates separate objects for 10, 20, "GfG", 40 and True, then
stores their memory addresses inside a.
 This means that modifying an element doesn’t affect other elements but can affect
the referenced object if it is mutable
Creating a List
Here are some common methods to create a list:
Using Square Brackets

# List of integers
a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'cherry']

# Mixed data types


c = [1, 'hello', 3.14, True]

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]

144 | P a g e
Using list() Constructor
We can also create a list by passing an iterable (like a string, tuple or another list)
to list() function.

# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)

Output
[1, 2, 3, 'apple', 4.5]

Creating List with Repeated Elements


We can create a list with repeated elements using the multiplication operator.

# Create a list [2, 2, 2, 2, 2]


a = [2] * 5

# Create a list [0, 0, 0, 0, 0, 0, 0]


b = [0] * 7

print(a)
print(b)

Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]

Accessing List Elements


Elements in a list can be accessed using indexing. Python indexes start at 0,
so a[0] will access the first element, while negative indexing allows us to access
elements from the end of the list. Like index -1 represents the last elements of list

a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])

Output
10
50

Adding Elements into List


145 | P a g e
We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.
 extend(): Adds multiple elements to the end of the list.
 insert(): Adds an element at a specific position.

# Initialize an empty list


a = []

# Adding 10 to end of list


a.append(10)
print("After append(10):", a)

# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", a)

# Adding multiple elements [15, 20, 25] at the end


a.extend([15, 20, 25])
print("After extend([15, 20, 25]):", a)

Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]

Updating Elements into List


We can change the value of an element by accessing it using its index.

a = [10, 20, 30, 40, 50]

# Change the second element


a[1] = 25
print(a)

Output
[10, 25, 30, 40, 50]

Removing Elements from List


We can remove elements from a list using:
 remove(): Removes the first occurrence of an element.
 pop(): Removes the element at a specific index or the last element if no index is
specified.
 del statement: Deletes an element at a specified index.

a = [10, 20, 30, 40, 50]

# Removes the first occurrence of 30


146 | P a g e
a.remove(30)
print("After remove(30):", a)

# Removes the element at index 1 (20)


popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)

# Deletes the first element (10)


del a[0]
print("After del a[0]:", a)

Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]

Iterating Over Lists


We can iterate the Lists easily by using a for loop or other iteration methods. Iterating
over lists is useful when we want to do some operation on each item or access
specific items based on certain conditions. Let's take an example to iterate over the list
using for loop.
Using for Loop

a = ['apple', 'banana', 'cherry']

# Iterating over the list


for item in a:
print(item)

Output
apple
banana
cherry
To learn various other methods, please refer to iterating over lists.
Nested Lists in Python
A nested list is a list within another list, which is useful for representing matrices or
tables. We can access nested elements by chaining indexes.

matrix = [
[1, 2, 3],
[4, 5, 6],

147 | P a g e
[7, 8, 9]
]

# Access element at row 2, column 3


print(matrix[1][2])

Output
6
To learn more, please refer to Multi-dimensional lists in Python
List Comprehension in Python
List comprehension is a concise way to create lists using a single line of code. It is
useful for applying an operation or filter to items in an iterable, such as a list or range.

# Create a list of squares from 1 to 5


squares = [x**2 for x in range(1, 6)]
print(squares)

Output
[1, 4, 9, 16, 25]
Explanation:
 for x in range(1, 6): loops through each number from 1 to 5 (excluding 6).
 x**2: squares each number x.
 [ ]: collects all the squared numbers into a new list.

Python List Quiz


Question 1. Find the output of the following program:
li = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
print (li[1][-1])
 A
r
 B
b
 C
D
 D
k
Explanation- li[1] refers to the second element 'Pratik'. li[1][-1] accesses the last character of
'Pratik', which is 'k'.
Question 2. Find the output of the following program:
li = [1, 2, 3, 4]
li.append([5,6,7,8])
print(li)
 A
[1,2,3,4,5,6,7,8]
 B

148 | P a g e
[1,2,3,4]
 C
[1,2,3,4,[5,6,7,8]]
 D
[1,2,3,4][5,6,7,8]
Explanation- The task of the append() method is to append a passed obj into an existing list.
But instead of passing a list to the append method will not merge the two lists, the entire list
which is passed is added as an element of the list.
Question 3. Find the output of the following program:
def addToList(a):
a += [10]
b = [10, 20, 30, 40]
addToList(b)
print (len(b))
 A
4
 B
5
 C
6
 D
10
Explanation- In Python, everything is a reference, and references are passed by value.
Parameter passing in Python is the same as reference passing in Java. As a consequence, the
function can modify the value referred by passed argument, i.e. the value of the variable in the
caller’s scope can be changed. Here the task of the function “addToList” is to add an element
10 in the list, So this will increase the length of the list by 1. So the output of the program is 5.
Question 4. Find the output of the following program:
a = ['Learn', 'Quiz', 'Practice', 'Contribute']
b=a
c = a[:]

b[0] = 'Code'
c[1] = 'Mcq'

count = 0
for c in (a, b, c):
if c[0] == 'Code':
count += 1
if c[1] == 'Mcq':
count += 10

print (count)
 A
4
 B
5
 C
11
 D

149 | P a g e
12
Explanation- When assigning a to b, we create a second reference to the same list. Changes
to b affect a. When assigning the slice of all elements in a to c, we are creating a full copy of a
which can be modified independently (i.e, any change in c will not affect a ).
So, while checking a ‘Code’ gets matched and the count increases to 1, but Mcq doesn't get
matched since its available only in c.
Now checking b here also ‘Code’ gets matched resulting in a count value to 2.
Finally while checking c which is separate from both a and b here only Mcq gets matched and
the count becomes 12.
Question 5. Find the output of the following program:
def gfg(x,li=[]):
for i in range(x):
li.append(i*i)
print(li)

gfg(3,[3,2,1])
 A
[3, 2, 1, 0, 1, 4]
 B
[0, 1, 0, 1, 4]
 C
[0, 1]
 D
[]
Explanation. The function appends squares of numbers from 0 to x-1 to the given list li. Since
the list [3,2,1] is passed explicitly, the result is [3, 2, 1, 0, 1, 4].
Question 6. Find the output of the following program:
# statement 1
li = range(100, 110)

# statement 2
print (li.index(105))
 A
105
 B
5
 C
106
 D
104
Explanation- Statement 1: will generate numbers from 100 to 110 and append all these
numbers in the list. Statement 2: will give the index value of 105 in the list list1.
Question 7. Find the output of the following program:
a = [1, 2, 3, 4, 5]
b=a
b[0] = 0;

print(a)

150 | P a g e
 A
[1, 2, 3, 4, 5, 0]
 B
[0,1, 2, 3, 4, 5]
 C
[0, 2, 3, 4, 5]
 D
[1, 2, 3, 4, 0]
Explanation- We have provided a reference to the list 'a' with another list 'b' meaning that
these two lists (a and b) references the same list. So any alteration with b will affect the original
list.
Question 8. Find the output of the following program:
a = [1998, 2002]
b = [2014, 2016]

print ((a + b)*2)


 A
[1998, 2002, 2014, 2016, 1998, 2002, 2014, 2016]
 B
[1998, 2002, 2014, 2016]
 C
[1998, 2002, 1998, 2002]
 D
[2014, 2016, 2014, 2016]
Explanation- When the addition(+) operator uses a list as its operands then the two lists will
get concatenated. And when a list id multiplied with a constant k>=0 then the same list is
appended k times in the original list.
Question 9. Find the output of the following program:
a = ['physics', 'chemistry', 1997, 2000]
print (a[1][-1])
 A
p
 B
y
 C
7
 D
2
Explanation- In python, we can slice a list but we can also slice an element within the list if it is
a string. The declaration list[x][y] will mean that ‘x’ is the index of the element within a list and ‘y’
is the index of an entity within that string.
Question 10. Find the output of the following program:
a = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']]
print(len(a))
 A
12
 B
11
 C
6
151 | P a g e
 D
22
Explanation- The beauty of python list datatype is that within a list, a programmer can nest
another list, a dictionary, or a tuple. Since in the code, there are 6 items present in the list the
length of the list is 6.
Question 11. Find the output of the following program:
a = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
print(a[0:6:2])
 A
['python', '@', 'for']
 B
[\'Geeks\', \'Geeks\', \'learning\']
 C
[\'python\', \'learning\', \'@\', \'Geeks\', \'for\', \'Geeks\']
 D
[\'python\', \'Geeks\']
Explanation- In python list slicing can also be done by using the syntax listName[x:y:z] where x
means the initial index, y-1 defines the final index value and z specifies the step size. If anyone
of the values among x, y, and z is missing the interpreter takes the default value.
Question 12. Find the output of the following program:
a = [10, 20, 30, 40, 50]
b = [1, 2, 3, 4, 5]

subtracted = list()
for a, b in zip(a, b):
item = a -b
subtracted.append(item)

print(subtracted)
 A
[10, 20, 30, 40, 50]
 B
[1, 2, 3, 4, 5]
 C
[10, 20, 30, 40, 50,-1, -2, -3, -4, -5]
 D
9, 18, 27, 36, 45
Explanation- The zip() function in Python combines multiple iterables such
as lists, tuples, strings, dict etc, into a single iterator of tuples where each tuple contains
elements from the input iterables at the same index.
In the given code the lists 'a' and 'b' are combined by the zip method and then the difference
between the elements from a and b are added to the new list ( subtracted ).
The output will be - 9, 18, 27, 36, 45
Question 13. Find the output of the following program:
li = ['a', 'b', 'c', 'd', 'e']
print(li[10:] )
 A
[\'a\', \'b\', \'c\', \'d\', \'e\']
 B

152 | P a g e
[ \'c\', \'d\', \'e\']
 C
[]
 D
[\'a\', \'b\']
Explanation- As one would expect, attempting to access a member of a list using an index that
exceeds the number of members (e.g., attempting to access list[10] in the list above) results in
an IndexError. However, attempting to access a slice of a list at a starting index that exceeds
the number of members in the list will not result in an IndexError and will simply return an empty
list.
Question 14. Question 15: Find the output of the following program:
li = ['a', 'b', 'c'] * -3
print(li)
 A
[\'a\', \'b\', \'c\', \'a\', \'b\', \'c\', \'a\', \'b\', \'c\']
 B
[\'c\', \'b\', \'a\', \'c\', \'b\', \'a\', \'c\', \'b\', \'a\']
 C
[]
 D
[\'a\', \'b\', \'c\']
Explanation- An expression list[listelements]*N where N is an integer appends N copies of list
elements in the original list. If N is a negative integer or 0 output will be an empty list else if N is
positive list elements will be added N times to the original list.
Question 15. Find the output of the following program:
li = [2, 3, 9]
li = [[x for x in[li]] for x in range(3)]
print (li)
 A
[[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]]
 B
[[2, 3, 9], [2, 3, 9], [2, 3, 9]]
 C
[[[2, 3, 9]], [[2, 3, 9]]]
 D
None of these
Explanation- [x for x in[li] returns a new list copying the values in the list li and the outer for
statement prints the newly created list 3 times.
Question 16. Find the output of the following program:
a = [x for x in range(5)]
b = [x for x in range(7) if x in a and x%2==0]
print(b)
 A
[0, 2, 4, 6]
 B
[0, 2, 4]
 C
[0, 1, 2, 3, 4, 5]
 D

153 | P a g e
Runtime error
Explanation- This statement checks whether the value lies in list data and if it does whether it’s
divisible by 2. It does so for x in (0, 7).
Question 17. Find the output of the following program:
a = ['Geeks', 'for', 'Geeks']
b = [i[0].upper() for i in a]
print(b)
 A
[‘G’, ‘F’, ‘G’]
 B
[‘GEEKS’, ‘FOR’, ‘GEEKS’]
 C
[‘GEEKS’]
 D
Compilation error
Explanation- The variable i is used to iterate over each element in list temp. i[0] represent the
character at 0th index of i and .upper() function is used to capitalize the character present at
i[0].
Question 18. Find the output of the following program:
a = 'Geeks 22536 for 445 Geeks'
b = [x for x in (int(x) for x in a if x.isdigit()) if x%2 == 0]
print(b)
 A
[2, 2, 6, 4, 4]
 B
Compilation error
 C
Runtime error
 D
[‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’]
Explanation- This is an example of nested list comprehension. The inner list created contains a
list of integers in temp. The outer list only procures that x which are a multiple of 2.
Question 19. Find the output of the following program:
a = [x for x in (x for x in 'Geeks 22966 for Geeks' if x.isdigit()) if
(x in ([x for x in range(20)]))]
print(a)
 A
[2, 2, 9, 6, 6]
 B
[]
 C
Compilation error
 D
Runtime error
Explanation- Since here x has not been converted to int, the condition in the if statement fails
and therefore, the list remains empty.
Question 20. Find the output of the following program:
a = []
a.append([1, [2, 3], 4])

154 | P a g e
a.extend([7, 8, 9])
print(a[0][1][1] + a[2])
 A
Type Error
 B
12
 C
11
 D
38
Explanation- In the print(), indexing is used. a[0] denotes [1, [2, 3], 4], a[0][1] denotes [2, 3],
a[0][1][1] = 3 and a[2] = 8. Thus, the two integers are added, 3 + 8 = 11 and output comes as
11.
Question 21. Find the output of the following program:
li = [1, 1.33, 'GFG', 0, 'NO', None, 'G', True]
val1, val2 = 0,''
for x in li:
if(type(x) == int or type(x) == float):
val1 += x
elif(type(x) == str):
val2 += x
else:
break
print(val1, val2)
 A
2 GFGNO
 B
2.33 GFGNOG
 C
2.33 GFGNONoneGTrue
 D
2.33 GFGNO
Explanation- val1 will only have integer and floating values val1 = 1 + 1.33 + 0 = 2.33 and val2
will have string values val2 =’GFG’ + ‘NO’ = ‘GFGNO’. String ‘G’ will not be part of val2 as the
for loop will break at None, thus ‘G’ will not be added to val2.
Question 22. Find the output of the following program:
a = [1, 2, 3, 4]
b=a
c = a.copy()
d=a
a[0] = [5]
print(a, b, c, d)
 A
[5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
 B
[[5], 2, 3, 4] [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4]
 C
[5, 2, 3, 4] [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4]
 D
[[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] [[5], 2, 3, 4]

155 | P a g e
Explanation- In the given code, b is a shallow copy of a, meaning it references the same list
as a, while c and d are not deep copies, as c is a shallow copy created using .copy() and d is a
reference to a. The modification a[0] = [5] replaces the first element of a with the list [5], which is
also reflected in b and d.
Question 23. Find the output of the following program:
li = [1, 3, 5, 7, 9]
print(li.pop(-3), end = ' ')
 A
5
 B
9
 C
7
 D
3
Explanation- pop() will delete and return the element whose index was passed as parameter.
li.pop(-3) will delete 5 and return 5, which is printed by print().
Question 24. Find the output of the following program:
def REVERSE(a):
a.reverse()
return(a)
def YKNJS(a):
b = []
b.extend(REVERSE(a))
print(b)

a = [1, 3.1, 5.31, 7.531]


YKNJS(a)
 A
[1, 3.1, 5.31, 7.531]
 B
[7.531, 5.31, 3.1, 1]
 C
IndexError
 D
AttributeError: ‘NoneType’ object has no attribute ‘REVERSE’
Explanation- REVERSE() reverses the list and returns it. YKNJS() adds reverse of a list L to
the empty list List. L = [1, 3.1, 5.31, 7.531], gets reversed and becomes [7.531, 5.31, 3.1, 1].
Question 25. Find the output of the following program:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']

pos = nameList.index("GeeksforGeeks")

print (pos * 3)
 A
GeeksforGeeks GeeksforGeeks GeeksforGeeks
 B
Harsh
 C
Harsh Harsh Harsh

156 | P a g e
 D
ValueError: \'GeeksforGeeks\' is not in list
Explanation- The task of the index is to find the position of a supplied value in a given list. In
the above program the supplied value is “GeeksforGeeks” and the list is nameList. As
GeeksforGeeks is not present in the list, an exception is thrown.

Python Tuples


A tuple in Python is an immutable ordered collection of elements.


 Tuples are similar to lists, but unlike lists, they cannot be changed after their
creation (i.e., they are immutable).
 Tuples can hold elements of different data types.
 The main characteristics of tuples are
being ordered , heterogeneous and immutable.

Creating a Tuple
A tuple is created by placing all the items inside parentheses (), separated by
commas. A tuple can have any number of items and they can be of different data
types.
Example:

tup = ()
print(tup)

# Using String
tup = ('Geeks', 'For')
print(tup)

# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))

# Using Built-in Function


tup = tuple('Geeks')
print(tup)

Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)

157 | P a g e
('G', 'e', 'e', 'k', 's')
Let's understand tuple in detail:
Creating a Tuple with Mixed Datatypes.
Tuples can contain elements of various data types, including other
tuples, lists, dictionaries and even functions.
Example:

tup = (5, 'Welcome', 7, 'Geeks')


print(tup)

# Creating a Tuple with nested tuples


tup1 = (0, 1, 2, 3)
tup2 = ('python', 'geek')
tup3 = (tup1, tup2)
print(tup3)

# Creating a Tuple with repetition


tup1 = ('Geeks',) * 3
print(tup1)

# Creating a Tuple with the use of loop


tup = ('Geeks')
n=5
for i in range(int(n)):
tup = (tup,)
print(tup)

Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)

Python Tuple Basic Operations


Below are the Python tuple operations.
 Accessing of Python Tuples
 Concatenation of Tuples
 Slicing of Tuple
 Deleting a Tuple
Accessing of Tuples
158 | P a g e
We can access the elements of a tuple by using indexing and slicing, similar to how
we access elements in a list. Indexing starts at 0 for the first element and goes up to n-
1, where n is the number of elements in the tuple. Negative indexing starts from -1 for
the last element and goes backward.
Example:

# Accessing Tuple with Indexing


tup = tuple("Geeks")
print(tup[0])

# Accessing a range of elements using slicing


print(tup[1:4])
print(tup[:3])

# Tuple unpacking
tup = ("Geeks", "For", "Geeks")

# This line unpack values of Tuple1


a, b, c = tup
print(a)
print(b)
print(c)

Output
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks

Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation combines two or
more tuples to create a new tuple.
Note: Only the same datatypes can be combined with concatenation, an error arises if
a list and a tuple are combined.

159 | P a g e
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 = tup1 + tup2


print(tup3)

Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of elements of the original
tuple. The slicing syntax is tuple[start:stop:step].
Note- Negative Increment values can also be used to reverse the sequence of
Tuples.

tup = tuple('GEEKSFORGEEKS')

# Removing First element


print(tup[1:])

# Reversing the Tuple

160 | P a g e
print(tup[::-1])

# Printing elements of a Range


print(tup[4:9])

Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')

Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of a tuple. However,
we can delete an entire tuple using del statement.
Note: Printing of Tuple after deletion results in an Error.

tup = (0, 1, 2, 3, 4)
del tup

print(tup)
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 6, in <module>
NameError: name 'tup' is not defined
Tuple Unpacking with Asterisk (*)
In Python, the " * " operator can be used in tuple unpacking to grab multiple items into
a list. This is useful when you want to extract just a few specific elements and collect
the rest together.

tup = (1, 2, 3, 4, 5)

a, *b, c = tup

print(a)
print(b)
print(c)

Output
1
[2, 3, 4]
5
Explanation:
 a gets the first item.
 c gets the last item.

161 | P a g e
 *b collects everything in between into a list.

Suggested Quiz
 10 Questions
1. How to create an empty tuple in Python?
 A
tup = ()
 B
tup = tuple()
 C
tup = []
 D
Both A and B
Explanation: Both () and tuple() create an empty tuple in Python.
2. What is the output of (1, 2, 3) + (4, 5, 6)?
 A
(1, 2, 3, 4, 5, 6)
 B
(5, 7, 9)
 C
TypeError
 D
(1, 2, 3, (4, 5, 6))
Explanation: The + operator concatenates tuples.
3. How can you access the second element of the tuple t = (1, 2, 3)?
 A
t[1]
 B
t[2]
 C
t.get(1)
 D
t(1)
Explanation: Tuple indices start from 0, so t[1] refers to the second element.
4. What is the output of ('repeat',) * 3?
 A
('repeat', 'repeat', 'repeat')
 B
(repeat, repeat, repeat)
 C
TypeError
 D
('repeatrepeatrepeat',)
Explanation: Multiplying a tuple repeats its content.
5. Which of the following is true for the tuple t = (1, 2, [3, 4])?
 A
Tuples cannot contain mutable objects like lists.
 B
t[2][0] = 5 is a valid operation.
 C

162 | P a g e
Tuples can be resized.
 D
Tuples can only contain integers.
Explanation: While tuples themselves are immutable, they can contain mutable objects like lists.
6. What happens if we try to assign a value to an element in a tuple?
 A
The tuple is updated.
 B
Nothing happens.
 C
An error is raised.
 D
The tuple is converted to a list.
Explanation: Tuples are immutable, so attempting to change an element raises a TypeError.
7. Which of the following methods is not available for tuples?
 A
.count()
 B
.index()
 C
.sort()
 D
.reverse()
Explanation: Tuples cannot be sorted in-place because they are immutable; hence no .sort() method.
8. Which of the following is a correct statement about tuple unpacking?
 A
x, y, z = (1, 2, 3) is an invalid statement.
 B
Tuple unpacking requires more variables than the elements in the tuple.
 C
Tuple unpacking can be done without matching the exact number of elements
 D
x, y, z = (1, 2, 3) unpacks the values into x, y, and z
Explanation: Tuple unpacking assigns each element of a tuple to a variable provided they match in
quantity.
9. What is the output of tuple(map(lambda x: x*x, [1, 2, 3]))?
 A
[1, 4, 9]
 B
(1, 4, 9)
 C
{1, 4, 9}
 D
None
Explanation: The map() function applies a function to every item of an iterable and tuple() converts the
result to a tuple.
10.What does the following tuple comprehension do? tuple(x for x in range(5))
 A
Creates a tuple with elements 0 to 4.

163 | P a g e
 B
Generates an error.
 C
Creates a list instead of a tuple.
 D
None of the above.
Explanation: This is a generator expression passed to the tuple() constructor, which creates a tuple
containing numbers from 0 to 4.

Dictionaries in Python

Python dictionary is a data structure that stores the value in key: value pairs. Values
in a dictionary can be of any data type and can be duplicated, whereas keys can't be
repeated and must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it
easier to find values.

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

How to Create a Dictionary


Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a 'comma'.

d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d1)

# create dictionary using dict() constructor


d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
 Dictionary keys are case sensitive: the same name but different cases of Key will
be treated distinctly.
 Keys must be immutable: This means keys can be strings, numbers or tuples but
not lists.

164 | P a g e
 Keys must be unique: Duplicate keys are not allowed and any duplicate key will
overwrite the previous value.
 Dictionary internally uses Hashing. Hence, operations like search, insert, delete can
be performed in Constant Time.
From Python 3.7 Version onward, Python dictionary are Ordered.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square brackets
or get() method.

d = { "name": "Prajjwal", 1: "Python", (1, 2): [1,2,4] }

# Access using key


print(d["name"])

# Access using get()


print(d.get("name"))

Output
Prajjwal
Prajjwal

Adding and Updating Dictionary Items


We can add new key-value pairs or update existing keys by using assignment.

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

# Adding a new key-value pair


d["age"] = 22

# Updating an existing value


d[1] = "Python dict"

print(d)

Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}

Removing Dictionary Items


We can remove items from dictionary using the following methods:
 del: Removes an item by key.
 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair.

d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}

165 | P a g e
# Using del to remove an item
del d["age"]
print(d)

# Using pop() to remove an item and return the value


val = d.pop(1)
print(val)

# Using popitem to removes and returns


# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")

# Clear all items from the dictionary


d.clear()
print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Key: 3, Value: Geeks
{}

Iterating Through a Dictionary


We can iterate over keys [using keys() method] , values [using values() method] or
both [using item() method] with a for loop.

d = {1: 'Geeks', 2: 'For', 'age':22}

# Iterate over keys


for key in d:
print(key)

# Iterate over values


for value in d.values():
print(value)

# Iterate over key-value pairs


for key, value in d.items():
print(f"{key}: {value}")

Output
1
2
age

166 | P a g e
Geeks
For
22
1: Geeks
2: For
age: 22
Read in detail: Ways to Iterating Over a Dictionary
Nested Dictionaries

Example of Nested Dictionary:

d = {1: 'Geeks', 2: 'For',


3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

print(d)

Output
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Read in Detail: Python Nested Dictionary
Copying Dictionaries in Python
A copy of a dictionary can be created using either shallow copy or deep
copy methods. These methods allow duplicating dictionary objects, but they behave
differently when it comes to nested data. Let's dicuss both in detail.
1. Shallow Copy
A shallow copy makes a new dictionary with same outer values as the original. But if
the dictionary has nested data (like a list or another dictionary), both copies still share
that inner data. So, changes to nested parts will affect other.
It is created using copy.copy() method from Python’s copy module.

167 | P a g e
Example:
This code shows that in a shallow copy, changes to nested data affect both the
original and the copy because the nested parts are shared.

import copy
original = {'name': 'Alice', 'marks': {'math': 90, 'science': 95}}

# Create a shallow copy


shallow = copy.copy(original)

# Modify nested value in the copy


shallow['marks']['math'] = 100

print("Original:", original)
print("Shallow Copy:", shallow)

Output
Original: {'name': 'Alice', 'marks': {'math': 100, 'science': 95}}
Shallow Copy: {'name': 'Alice', 'marks': {'math': 100, 'science': 95}}
Explanation:
 shallow = copy.copy(original): creates a shallow copy, nested 'marks' remains
shared.
 shallow['marks']['math'] = 100: updates 'math' in the shared nested dictionary.
 print(original), print(shallow): both show updated 'math' value due to shared
data.
2. Deep Copy
A deep copy makes a new dictionary and also creates separate copies of all nested
data (like lists or other dictionaries). This means original and copy are completely
independent, changes made to nested parts do not affect other.
It is created using copy.deepcopy() method from Python’s copy module.
Example:
This Example shows that a deep copy creates a fully independent copy of both the
outer and nested data, so changes in the copy do not affect the original.

import copy
original = {'name': 'Alice', 'marks': {'math': 90, 'science': 95}}

# Create a deep copy


deep = copy.deepcopy(original)

# Modify nested value in the deep copy


deep['marks']['math'] = 100

print("Original:", original)
print("Deep Copy:", deep)

168 | P a g e
Try it on GfG Practice

Output
Original: {'name': 'Alice', 'marks': {'math': 90, 'science': 95}}
Deep Copy: {'name': 'Alice', 'marks': {'math': 100, 'science': 95}}
Explanation:
 deep = copy.deepcopy(original): creates a deep copy, nested 'marks' is also
copied separately.
 deep['marks']['math'] = 100: updates 'math' in the deep copy’s nested dictionary
only.
 print(original), print(deep): original remains unchanged, only deep copy shows
the updated 'math' value.

Python Tuples Quiz


Question 1
What is the output of the following program?
tup = (1, 2, 3, 4)
tup.append( (5, 6, 7) )
print(len(tup))
 A
1
 B
2
 C
5
 D
Error
Explanation- In this case, an exception will be thrown as tuples are immutable and don’t have
an append method.
Question 2. What is the output of the following program?
tup = {}
tup[(1,2,4)] = 8
tup[(4,2,1)] = 10
tup[(1,2)] = 12
sum1 = 0
for k in tup:
sum1 += tup[k]
print(len(tup) + sum1)
 A
30
 B
31
 C

169 | P a g e
32
 D
33
Explanation- {} creates an empty dictionary, not a tuple. The dictionary tup is assigned three
key-value pairs where the keys are tuples: {(1,2,4): 8, (4,2,1): 10, (1,2): 12}. Therefore
dictionary length is 3.
 Summing the values: 8 + 10 + 12 = 30. Adding the dictionary length (3 + 30) hence, the final output
is 33.
Question 3. What is the output of the following program?
tup1 = (1, 2, 4, 3)
tup2 = (1, 2, 3, 4)
print(tup1 < tup2)
 A
Error
 B
True
 C
False
 D
Unexpected
Explanation- In this case elements will be compared one by one. So, when it compares 4 with
3 it will return False.
Question 4. What is the output of the following program?
tup = (1, 2, 3)
print(2 * tup)
 A
(1, 2, 3, 1, 2, 3)
 B
(1, 2, 3, 4, 5, 6)
 C
(3, 6, 9)
 D
Error
Explanation- The ‘*’ operator is used to concatenate tuples.
Question 5. What is the output of the following program?
tup=("Check")*3
print(tup)
 A
Unexpected
 B
3Check
 C
CheckCheckCheck
 D
Syntax Error
Explanation- Here (“Check”) will be treated as is a string not a tuple as there is no comma after
the element.
Question 6. What is the output of the following program?
s = 'geeks'

170 | P a g e
a, b, c, d, e = s
b = c = '*'
s = (a, b, c, d, e)
print(s)
 A
(‘g’, ‘*’, ‘*’, ‘k’, ‘s’)
 B
(‘g’, ‘e’, ‘e’, ‘k’, ‘s’)
 C
(‘geeks’, ‘*’, ‘*’)
 D
KeyError
Explanation- A tuple is created as T = (‘g’, ‘e’, ‘e’, ‘k’, ‘s’), then it is unpacked into a, b, c, d and
e, mapping from ‘g’ to a and ‘s’ to e. b and c which are both ‘e’ are equal to ‘*’ and then the
existing tuple is replaced by packing a, b, c, d and e into a tuple T.
Question 7. What is the output of the following program?
tup = (2e-04, True, False, 8, 1.001, True)
val = 0
for x in tup:
val += int(x)
print(val)
 A
12
 B
11
 C
11.001199999999999
 D
TypeError
Explanation- Integer value of 2e-04(0.0002) is 0, True holds a value 1 and False a 0, integer
value of 1.001 is 1. Thus total 0 + 1 + 0 + 8 + 1 + 1 = 11.
Question 8. What is the output of the following program?
li = [3, 1, 2, 4]
tup = ('A', 'b', 'c', 'd')
li.sort()
counter = 0
for x in tup:
li[counter] += int(x)
counter += 1
break
print(li)
 A
[66, 97, 99, 101]
 B
[66, 68, 70, 72]
 C
[66, 67, 68, 69]
 D
ValueError
Explanation- The code attempts to convert 'A' to int, which raises ValueError before completing
the loop.
171 | P a g e
Question 9. What is the output of the following program?
li = [2e-04, 'a', False, 87]
tup = (6.22, 'boy', True, 554)
for i in range(len(li)):
if li[i]:
li[i] = li[i] + tup[i]
else:
tup[i] = li[i] + li[i]
break
 A
[6.222e-04, ‘aboy’, True, 641]
 B
[6.2202, ‘aboy’, 1, 641]
 C
TypeError
 D
[6.2202, ‘aboy’, False, 87]
Explanation- The for loop will run for i = 0 to i = 3, i.e. 4 times(len(L) = 4). 2e-04 is same as
0.0002, thus L[i] = 6.22 + 0.0002 = 6.2202. String addition will result in concatenation, ‘a’ + ‘boy’
= ‘aboy’. False + True is True, it’ll return the integer value of 1. As tuples are immutable, the
code will end with TypeError, but elements of li will be updated.
Question 10. What is the output of the following program?
import sys
tup = tuple()
print(sys.getsizeof(tup), end = " ")
tup = (1, 2)
print(sys.getsizeof(tup), end = " ")
tup = (1, 3, (4, 5))
print(sys.getsizeof(tup), end = " ")
tup = (1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3))
print(sys.getsizeof(tup))
 A
0 2 3 10
 B
32 34 35 42
 C
48 64 72 128
 D
48 144 192 480
Explanation- An Empty Tuple has 48 Bytes as Overhead size and each additional element
requires 8 Bytes. (1, 2) Size: 48 + 2 * 8 = 64 (1, 3, (4, 5)) Size: 48 + 3 * 8 = 72 (1, 2, 3, 4, 5, [3,
4], ‘p’, ‘8’, 9.777, (1, 3)) Size: 48 + 10 * 8 = 128
Question 11. What is the output of the following program?
tup1 = (1)
tup2 = (3, 4)
tup1 += 5
print(tup1)
 A
TypeError
 B

172 | P a g e
(1, 5, 3, 4)
 C
1 TypeError
 D
6
Explanation- tup1 = (1): This is not a tuple, it’s just the integer 1 inside parentheses. To create
a tuple with one element, you need a comma: (1,).
 So, tup1 is an integer 1.
 tup1 += 5 means tup1 = tup1 + 5, which equals 1 + 5 = 6.
 print(tup1) outputs 6.

Python Dictionary Quiz


Question 1
Find the output of the following program:
d = dict()
for x in enumerate(range(2)):
d[x[0]] = x[1]
d[x[1]+7] = x[0]
print(d)
 A
{0: 1, 7: 0, 1: 1, 8: 0}
 B
{1: 1, 7: 2, 0: 1, 8: 1}
 C
{0: 0, 7: 0, 1: 1, 8: 1}
 D
KeyError
Explanation
enumerate() will return a tuple, the loop will have x = (0, 0), (1, 1). Thus D[0] = 0, D[1] = 1, D[0
+ 7] = D[7] = 0 and D[1 + 7] = D[8] = 1.
Note: Dictionary is unordered, so the sequence of the key-value pair may differ in each output.
Question 2
Find the output of the following program:
d = {1 : 1, 2 : '2', '1' : 1, '2' : 3}
d['1'] = 2
print(d[d[d[str(d[1])]]])
 A
2
 B
3
 C
\'2\'
 D
KeyError
Explanation
Simple key-value pair is used recursively, D[1] = 1, str(1) = ‘1’. So, D[str(D[1])] = D[‘1’] = 2, D[2]
= ‘2’ and D[‘2’] = 3.
Question 3
173 | P a g e
Find the output of the following program:
d = {1 : {'A' : {1 : "A"}, 2 : "B"}, 3 :"C", 'B' : "D", "D": 'E'}
print(d[d[d[1][2]]], end = " ")
print(d[d[1]["A"][2]])
 A
CB
 B
E Key Error
 C
BD
 D
DB
Explanation
Key-Value Indexing is used in the example above. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][2] = “B”,
D[D[1][2]] = D[“B”] = “D” and D[“D”] = “E”. D[1] = {‘A’ : {1 : “A”}, 2 : “B”}, D[1][“A”] = {1 : “A”} and
D[1][“A”][2] doesn’t exists, thus KeyError.
Question 4
Find the output of the following program:
d = dict()
for i in range (3):
for j in range(2):
d[i] = j
print(d)
 A
{0: 0, 1: 0, 2: 0}
 B
{0: 1, 1: 1, 2: 1}
 C
{0: 0, 1: 0, 2: 0, 0: 1, 1: 1, 2: 1}
 D
TypeError: Immutable object
Explanation
1st loop will give 3 values to i 0, 1 and 2. In the empty dictionary, valued are added and
overwrited in j loop, for eg. D[0] = [0] becomes D[0] = 1, due to overwriting.
Question 5
Question 5:Find the output of the following program:
d = {1 : [1, 2, 3], 2: (4, 6, 8)}
d[1].append(4)
print(d[1], end = " ")
li = [d[2]]
li.append(10)
d[2] = tuple(L)
print(d[2])
 A
[1, 2, 3, 4] ((4, 6, 8), 10)
 B
[1, 2, 3, 4] (4, 6, 8, 10)
 C
[1, 2, 3, 4] TypeError: tuples are immutable
 D
[1, 2, 3, 4] [4, 6, 8, 10]

174 | P a g e
Explanation
In the first part, key-value indexing is used and 4 is appended into the list. As tuples are
immutable, in the second part the tuple is converted into a list, and value 10 is added finally
then converted back to tuple.
Question 6
What will be the output of the following code?
s = "GeeksforGeeks"
print(s[0], s[-1])
 A
GG
 B
Gs
 C
Gk
 D
ek
Explanation
s[0] accesses the first character 'G' and s[-1] accesses the last character 's'.
Question 7
Find the output of the following program:
a = {}
a.fromkeys(['a', 'b', 'c', 'd'], 98)
print (a)
 A
Syntax error
 B
{‘a’:98, ‘b’:98, ‘c’:98, ‘d’:98}
 C
{‘a’:None, ‘b’:None, ‘c’:None.’d’:None}
 D
{}
Explanation
fromkeys() method returns a new dictionary but does not modify the original dictionary a, so
print(a) outputs { } (empty dictionary).
Question 8
Find the output of the following program:
dict ={}
print (all(dict))
 A
{}
 B
False
 C
True
 D
An exception is thrown
Explanation
The all() method returns:
 True – If all elements in an iterable are true ot iterable is empty.

175 | P a g e
 False – If any element in an iterable is false.
Question 9
Find the output of the following program:
a = {'geeks' : 1, 'gfg' : 2}
b = {'geeks' : 2, 'gfg' : 1}
print (a == b)
 A
True
 B
False
 C
Error
 D
None
Explanation
If two dictionary are the same it returns true, otherwise it returns false.
Question 10
Which of the following is FALSE about dictionary?
 A
The values of a dictionary can be accessed using keys
 B
The keys of a dictionary can be accessed using values
 C
Both of the above
 D
None of the above
Explanation
The values of a dictionary can be accessed using keys but the keys of a dictionary can’t be
accessed using values.
Question 11
Find the output of the following program:
d = {'GFG' : 'geeksforgeeks.org',
'google' : 'google.com',
'facebook' : 'facebook.com'
}
del d['google'];
for key, values in d.items():
print(key, end=" ")
d.clear();
for key, values in d.items():
print(key)
del d;
for key, values in d.items():
print(key)
 A
Both B and D
 B
GFG facebook
 C
facebook GFG
 D
NameError: name 'dictionary' is not defined
176 | P a g e
Explanation
The statement: del dictionary; removes the entire dictionary, so iterating over a deleted
dictionary throws a runtime error as follows:
Traceback (most recent call last): File "cbeac2f0e35485f19ae7c07f6b416e84.py", line 12, in for key,
values in dictionary.items(): NameError: name 'dictionary' is not defined

Question 12
Find the output of the following program:
d1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
d2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
d1.update(d2);
for key, values in d1.items():
print(key, values , end=" ")
 A
Google 1 Facebook 2 Microsoft 2 GFG 1 Youtube 3
 B
Runtime error
 C
Compilation error
 D
None of these
Explanation
dictionary1.update(dictionary2) is used to update the entries of dictionary1 with entries of
dictionary2. If there are same keys in two dictionaries, then the value in the second dictionary is
used.
Question 13
Find the output of the following program:
d1 = {'GFG' : 1,
'Google' : 2,
'GFG' : 3
}
print(d1['GFG']);
 A
Compilation error due to duplicate keys
 B
Runtime time error due to duplicate keys
 C
3
 D
1
Explanation
Here, GFG is the duplicate key. Duplicate keys are not allowed in python. If there are same
keys in a dictionary, then the value assigned mostly recently is assigned to that key.
Question 14
Find the output of the following program:
177 | P a g e
d = dict()
d['key1'] = {'key1' : 44, 'key2' : 566}
d['key2'] = [1, 2, 3, 4]
for (key, values) in d.items():
print(values, end = "")
 A
Compilation error
 B
{'key1': 44, 'key2': 566}[1, 2, 3, 4]
 C
Runtime error
 D
None of the above
Explanation
A dictionary can hold any value such as an integer, string, list or even another dictionary
holding key value pairs.
Question 15
Find the output of the following program:
d = {'GFG' : 1,
'Facebook' : 2,
'Google' : 3
}
for (key, values) in d.items():
print(key, values, end = " ")
 A
GFG 1 Facebook 2 Google 3
 B
Facebook 2 GFG 1 Google 3
 C
Facebook 2 Google 3 GFG 1
 D
Any of the above
Explanation
Dictionaries were unordered in Python versions before 3.7, so the output order can vary in older
versions, matching option D.
In Python 3.7 and later, dictionaries keep the order of insertion, so the output will match the
order items were added, hence the option 'A' is correct..
Question 16
Find the output of the following program:
d = {}
d[(1,2,4)] = 8
d[(4,2,1)] = 10
d[(1,2)] = 12

sum = 0
for k in d:
sum += d[k]

print (len(d) + sum)


 A
33

178 | P a g e
 B
12
 C
10
 D
8
Explanation
Tuples can be used for keys into dictionary. The tuples can have mixed length and the order of
the items in the tuple is considered when comparing the equality of the keys.
Question 17
Find the output of the following program:
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
print (d1 > d2)
 A
True
 B
False
 C
Compilation Error
 D
TypeError
Explanation
The ‘>’ operator is not supported between instances of two dictionaries in Python 3.
Question 18
Find the output of the following program:
d = {"geek":10, "for":45, "geeks": 90}
print("geek" in d)
 A
10
 B
False
 C
True
 D
Error
Discuss it

Explanation
in is used to check the key exist in the dictionary or not.
Question 19
Find the output of the following program:
d ={1:"geek", 2:"for", 3:"geeks"}
del d
 A
del deletes the entire dictionary
 B
del doesn’t exist for the dictionary
 C
del deletes the keys in the dictionary
 D

179 | P a g e
del deletes the values in the dictionary
Explanation
del deletes the entire dictionary and any further attempt to access it will throw an error.
Question 20
Find the output of the following program:
a = {}
a[1] = 1
a['1'] = 2
a[1]= a[1]+1
count = 0
for i in a:
count += a[i]
print(count)
 A
2
 B
4
 C
1
 D
Error
Explanation
The above piece of code basically finds the sum of the values of keys.
Question 21
Find the output of the following program:
d = {1:'A', 2:'B', 3:'C'}
del d[1]
d[1] = 'D'
del d[2]
print(len(d))
 A
Error
 B
0
 C
1
 D
2
Explanation
After the key-value pair of 1:’A’ is deleted, the key-value pair of 1:’D’ is added.
Question 22
Find the output of the following program:
a ={}
a['a']= 1
a['b']=[2, 3, 4]
print(a)
 A
{‘b’: [2], ‘a’: 1}
 B
{'a': 1, 'b': [2, 3, 4]}
 C

180 | P a g e
{‘b’: [2], ‘a’: [3]}
 D
Error
Explanation
Mutable members can be used as the values of the dictionary but they cannot be used as the
keys of the dictionary
Question 23
Find the output of the following program:
d = {1:'1', 2:'2', 3:'3'}
del d[1]
d[1] = '10'
del d[2]
print (len(d) )
 A
1
 B
2
 C
3
 D
4
Explanation
The task of the ‘del’ function is to remove key-value pairs from a dictionary. Initially the size of
the given dictionary was 3. Then the key value pair for key 1 is first removed and then added
back with a new value. Then the key value pair for key 2 is removed. So, finally the size of the
dictionary is 2.
Question 24
Find the output of the following program:
d = {}

def addTodict(country):
if country in d:
d[country] += 1
else:
d[country] = 1

addTodict('China')
addTodict('Japan')
addTodict('china')

print (len(d))
 A
0
 B
1
 C
2
 D
3
Explanation

181 | P a g e
The task of “len” function is to return the number of keys in a dictionary. Here 3 keys are added
to the dictionary “country” using the “addToCounter” function. The keys to a dictionary are case
sensitive.

Python Sets


In Python, array is a collection of items stored at contiguous memory locations. The idea is to
store multiple items of the same type together. Unlike Python lists (can store elements of mixed
types), arrays must have all elements of same type. Having only homogeneous elements
makes it memory-efficient.
Python Array Example:

import array as arr


a = arr.array('i', [1, 2, 3])

# accessing First Araay


print(a[0])

# adding element to array


a.append(5)
print(a)

Output
1
array('i', [1, 2, 3, 5])

Create an Array in Python


Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python with data
type and value list specified in its arguments.

import array as arr


a = arr.array('i', [1, 2, 3])

for i in range(0, 3):


print(a[i], end=" ")

Output
1 2 3

Adding Elements to a Set in Python


182 | P a g e
We can add items to a set using add() method and update() method. add() method
can be used to add only a single item. To add multiple items we use update() method.
Example:

# Creating a set
set1 = {1, 2, 3}

# Add one item


set1.add(4)

# Add multiple items


set1.update([5, 6])

print(set1)

Output
{1, 2, 3, 4, 5, 6}

Accessing a Set in Python


We can loop through a set to access set items as set is unindexed and do not support
accessing elements by indexing. Also we can use in keyword which is membership
operator to check if an item exists in a set.
Example:

set1 = set(["Geeks", "For", "Geeks."])

# Accessing element using For loop


for i in set1:
print(i, end=" ")

# Checking the element# using in keyword


print("Geeks" in set1)

Output
Geeks For Geeks. True
Explanation:
 This loop will print each item in the set. Since sets are unordered, the order of items
printed is not guaranteed.
 This code checks if the number 4 is in set1 and prints a corresponding message.
Removing Elements from the Set in Python
We can remove an element from a set in Python using several methods: remove(),
discard() and pop(). Each method works slightly differently :
 Using remove() Method or discard() Method
 Using pop() Method
 Using clear() Method

183 | P a g e
Using remove() Method or discard() Method
remove() method removes a specified element from the set. If the element is not
present in the set, it raises a KeyError. discard() method also removes a specified
element from the set. Unlike remove(), if the element is not found, it does not raise an
error.

# Using Remove Method


set1 = {1, 2, 3, 4, 5}
set1.remove(3)
print(set1)

# Attempting to remove an element that does not exist


try:
set1.remove(10)
except KeyError as e:
print("Error:", e)

# Using discard() Method


set1.discard(4)
print(set1)

# Attempting to discard an element that does not exist


set1.discard(10) # No error raised
print(set1)

Output
{1, 2, 4, 5}
Error: 10
{1, 2, 5}
{1, 2, 5}

Using pop() Method


pop() method removes and returns an arbitrary element from the set. This means we
don't know which element will be removed. If the set is empty, it raises a KeyError.
Note: If the set is unordered then there's no such way to determine which element is
popped by using the pop() function.

set1 = {1, 2, 3, 4, 5}
val = set1.pop()
print(val)
print(set1)

# Using pop on an empty set


set1.clear() # Clear the set to make it empty
try:
set1.pop()
except KeyError as e:

184 | P a g e
print("Error:", e)

Output
1
{2, 3, 4, 5}
Error: 'pop from an empty set'

Using clear() Method


clear() method removes all elements from the set, leaving it empty.

set1 = {1, 2, 3, 4, 5}
set1.clear()
print(set1)

Output
set()

Frozen Sets in Python


A frozenset in Python is a built-in data type that is similar to a set but with one key
difference that is immutability. This means that once a frozenset is created, we cannot
modify its elements that is we cannot add, remove or change any items in it. Like
regular sets, a frozenset cannot contain duplicate elements.
If no parameters are passed, it returns an empty frozenset.

# Creating a frozenset from a list


fset = frozenset([1, 2, 3, 4, 5])
print(fset)

# Creating a frozenset from a set


set1 = {3, 1, 4, 1, 5}
fset = frozenset(set1)
print(fset)

Output
frozenset({1, 2, 3, 4, 5})
frozenset({1, 3, 4, 5})

Typecasting Objects into Sets


Typecasting objects into sets in Python refers to converting various data types into a
set. Python provides the set() constructor to perform this typecasting, allowing us to
convert lists, tuples and strings into sets.

# Typecasting list into set


li = [1, 2, 3, 3, 4, 5, 5, 6, 2]
set1 = set(li)

185 | P a g e
print(set1)

# Typecasting string into set


s = "GeeksforGeeks"
set1 = set(s)
print(set1)

# Typecasting dictionary into set


d = {1: "One", 2: "Two", 3: "Three"}
set1 = set(d)
print(set1)

Output
{1, 2, 3, 4, 5, 6}
{'f', 'G', 's', 'k', 'r', 'e', 'o'}
{1, 2, 3}
Advantages of Set in Python
 Unique Elements: Sets can only contain unique elements, so they can be useful
for removing duplicates from a collection of data.
 Fast Membership Testing: Sets are optimized for fast membership testing, so
they can be useful for determining whether a value is in a collection or not.
 Mathematical Set Operations: Sets support mathematical set operations like
union, intersection and difference, which can be useful for working with sets of
data.
 Mutable: Sets are mutable, which means that you can add or remove elements
from a set after it has been created.
Disadvantages of Sets in Python
 Unordered: Sets are unordered, which means that you cannot rely on the order
of the data in the set. This can make it difficult to access or process data in a
specific order.
 Limited Functionality: Sets have limited functionality compared to lists, as they
do not support methods like append() or pop(). This can make it more difficult to
modify or manipulate data stored in a set.
 Memory Usage: Sets can consume more memory than lists, especially for small
datasets. This is because each element in a set requires additional memory to
store a hash value.

186 | P a g e
 Less Commonly Used: Sets are less commonly used than lists and dictionaries
in Python, which means that there may be fewer resources or libraries available
for working with them. This can make it more difficult to find solutions to problems
or to get help with debugging.
Overall, sets can be a useful data structure in Python, especially for removing
duplicates or for fast membership testing. However, their lack of ordering and limited
functionality can also make them less versatile than lists or dictionaries, so it is
important to carefully consider the advantages and disadvantages of using sets when
deciding which data structure to use in your Python program.
Set Methods in Python

Function Description

add() Adds an element to a set

remove() Removes an element from a set. If the element is not


present in the set, raise a KeyError

clear() Removes all elements form a set

copy() Returns a shallow copy of a set

pop() Removes and returns an arbitrary set element. Raise


KeyError if the set is empty

update() Updates a set with the union of itself and others

union() Returns the union of sets in a new set

difference() Returns the difference of two or more sets as a new set

difference_update() Removes all elements of another set from this set

discard() Removes an element from set if it is a member. (Do


nothing if the element is not in set)

intersection() Returns the intersection of two sets as a new set

187 | P a g e
Function Description

intersection_update() Updates the set with the intersection of itself and


another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

symmetric_difference() Returns the symmetric difference of two sets as a new


set

symmetric_difference_u Updates a set with the symmetric difference of itself


pdate() and another

Python Arrays


Lists in Python are the most flexible and commonly used data structure for sequential
storage. They are similar to arrays in other languages but with several key differences:
 Dynamic Typing: Python lists can hold elements of different types in the same list.
We can have an integer, a string and even other lists all stored within a single list.
 Dynamic Resizing: Lists are dynamically resized, meaning you can add or remove
elements without declaring the size of the list upfront.
 Built-in Methods: Python lists come with numerous built-in methods that allow for
easy manipulation of the elements within them, including methods for appending,
removing, sorting and reversing elements.
Example:

a = [1, "Hello", [3.14, "world"]]


a.append(2) # Add an integer to the end
print(a)

Output
[1, 'Hello', [3.14, 'world'], 2]

188 | P a g e
Note: Python does not have built-in array support in the same way that languages like
C and Java do, but it provides something similar through the array module for storing
elements of a single type.
NumPy Arrays
NumPy arrays are a part of the NumPy library, which is a powerful tool for numerical
computing in Python. These arrays are designed for high-performance operations on
large volumes of data and support multi-dimensional arrays and matrices. This makes
them ideal for complex mathematical computations and large-scale data processing.
Key Features:
 Multi-dimensional support: NumPy arrays can handle more than one dimension,
making them suitable for matrix operations and more complex mathematical
constructs.
 Broad broadcasting capabilities: They can perform operations between arrays of
different sizes and shapes, a feature known as broadcasting.
 Efficient storage and processing: NumPy arrays are stored more efficiently than
Python lists and provide optimized performance for numerical operations.
Example :

import numpy as np
a = np.array([1, 2, 3, 4])

# Element-wise operations
print(a * 2)

# Multi-dimensional array
res = np.array([[1, 2], [3, 4]])
print(res * 2)

Output
[2 4 6 8]
[[2 4]
[6 8]]
Note: Choose NumPy arrays for scientific computing, where you need to handle
complex operations or work with multi-dimensional data.
Use Python's array module when you need a basic, memory-efficient container for
large quantities of uniform data types, especially when your operations are simple and
do not require the capabilities of NumPy.
Python Arrays
In Python, array is a collection of items stored at contiguous memory locations. The
idea is to store multiple items of the same type together. Unlike Python lists (can store
elements of mixed types), arrays must have all elements of same type. Having only
homogeneous elements makes it memory-efficient.
Python Array Example:

189 | P a g e
import array as arr
a = arr.array('i', [1, 2, 3])

# accessing First Araay


print(a[0])

# adding element to array


a.append(5)
print(a)

Output
1
array('i', [1, 2, 3, 5])

Create an Array in Python


Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python with data
type and value list specified in its arguments.

import array as arr


a = arr.array('i', [1, 2, 3])

for i in range(0, 3):


print(a[i], end=" ")

Output

1 2 3

Python Array Index

Adding Elements to an Array


Elements can be added to the Python Array by using built-in insert() function. Insert is
used to insert one or more data elements into an array. Based on the requirement, a
190 | P a g e
new element can be added at the beginning, end, or any given index of
array. append() is also used to add the value mentioned in its arguments at the end of
the Python array.

import array as arr


a = arr.array('i', [1, 2, 3])
print(*a)

a.insert(1, 4) # Insert 4 at index 1


print(*a)

Output
1 2 3
1 4 2 3
Note: We have used *a and *b for unpacking the array elements.
Accessing Array Items
In order to access the array items refer to the index number. Use the index operator [ ]
to access an item in a array in Python. The index must be an integer.

import array as arr


a = arr.array('i', [1, 2, 3, 4, 5, 6])

print(a[0])
print(a[3])

b = arr.array('d', [2.5, 3.2, 3.3])


print(b[1])
print(b[2])

Output
1
4
3.2
3.3

Removing Elements from the Array


Elements can be removed from the Python array by using built-in remove() function. It
will raise an Error if element doesn’t exist. Remove() method only removes the first
occurrence of the searched element. To remove range of elements, we can use an
iterator.
pop() function can also be used to remove and return an element from the array. By
default it removes only the last element of the array. To remove element from a
specific position, index of that item is passed as an argument to pop() method.

191 | P a g e
import array
a = array.array('i', [1, 2, 3, 1, 5])

# remove first occurance of 1


a.remove(1)
print(a)

# remove item at index 2


a.pop(2)
print(a)

Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])

Slicing of an Array
In Python array, there are multiple ways to print the whole array with all the elements,
but to print a specific range of elements from the array, we use Slice operation .

Python Index Slicing


 Elements from beginning to a range use [:Index]
 Elements from end use [:-Index]
 Elements from specific Index till the end use [Index:]
 Elements within a range, use [Start Index:End Index]
 Print complete List, use [:].
 For Reverse list, use [::-1].
import array as arr
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = arr.array('i', a)

res = a[3:8]
192 | P a g e
print(res)

res= a[5:]
print(res)

res= a[:]
print(res)

Output
[4, 5, 6, 7, 8]
[6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Searching Element in an Array


In order to search an element in the array we use a python in-built index() method.
This function returns the index of the first occurrence of value mentioned in
arguments.

import array
a = array.array('i', [1, 2, 3, 1, 2, 5])

# index of 1st occurrence of 2


print(a.index(2))

# index of 1st occurrence of 1


print(a.index(1))

Output
1
0

Updating Elements in an Array


In order to update an element in the array we simply reassign a new value to the
desired index we want to update.

import array
a = array.array('i', [1, 2, 3, 1, 2, 5])

# update item at index 2


a[2] = 6
print(a)

# update item at index 4


a[4] = 8
print(a)

193 | P a g e
Output
array('i', [1, 2, 6, 1, 2, 5])
array('i', [1, 2, 6, 1, 8, 5])

Different Operations on Python Arrays


Counting Elements in an Array
We can use count() method to count given item in array.

import array
a = array.array('i', [1, 2, 3, 4, 2, 5, 2])

count = a.count(2)
print(count)

Output
3

Reversing Elements in an Array


In order to reverse elements of an array we need to simply use reverse method.

import array
a = array.array('i', [1, 2, 3, 4, 5])

a.reverse()
print(*a)

Output
5 4 3 2 1

Extend Element from Array


In Python, an array is used to store multiple values or elements of the same datatype
in a single variable. The extend() function is simply used to attach an item from
iterable to the end of the array. In simpler terms, this method is used to add an array of
values to the end of a given or existing array.
list.extend(iterable)
Here, all the element of iterable are added to the end of a.

import array as arr


a = arr.array('i', [1, 2, 3,4,5])

a.extend([6,7,8,9,10])
print(a)

Output

194 | P a g e
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Python Arrays
In Python, arrays are a data structure that allows you to store multiple items of the same data type
in a single variable.
Question 1. What is the output of the following code?
from array import array
arr = array('i', [1, 2, 3, 4, 5])
print(arr[0])

 A
0
 B
1
 C
5
 D
Error
Explanation- Unlike Python’s built-in list, the array module is for homogeneous arrays (all
elements must be of the same type) hence 'i' denotes "unsigned integers" and then accessing
the first element of the array returns the value 1.
Question 2. Which of the following is the correct way to create an array in Python using the array
module?
 A
array = [1, 2, 3]
 B
array = array('i', [1, 2, 3])
 C
array = (1, 2, 3)
 D
array = {1, 2, 3}
Explanation- array module in Python is used to create an array, which is different from lists
Question 3. Which of the following methods is used to add an element to the end of an array?
 A
insert()
 B
append()
 C
extend()
 D
add()
Explanation- The append method adds an element to the end of the array.
Question 4. How to create an empty array of integers in Python using the array module?
 A
arr = array('i')
 B
arr = array('i', [])
 C
Both a and b
 D

195 | P a g e
None of the above
Explanation- Both array('i') and array('i', []) can be used to create an empty array of integers.
Question 5. What will be the output of the following code?
from array import array
arr = array('i', [1, 2, 3])
arr.insert(1, 4)
print(arr)

 A
array('i', [1, 4, 2, 3])
 B
array('i', [4, 1, 2, 3])
 C
array('i', [1, 2, 3, 4])
 D
Error
Question 6. What does the index method do in an array?
 A
Returns the last occurrence of a specified value
 B
Inserts a value at a specified position
 C
Returns the index of the first occurrence of a specified value
 D
Removes an element at a specified position
Explanation- The index method returns the index of the first occurrence of a specified value.
Question 7. What does the following code print?
from array import array
arr = array('i', [1, 2, 3])
arr[1] = 5
print(arr)

 A
array('i', [1, 2, 3])
 B
array('i', [5, 2, 3])
 C
array('i', [1, 5, 3])
 D
Error
Explanation- Assigning a new value to an element at a specific index updates the array.
Question 8. What is the result of the following code?
from array import array
arr1 = array('i', [1, 2, 3])
arr2 = array('i', [4, 5])
arr1 += arr2
print(arr1)

 A
array('i', [1, 2, 3, 4, 5])
 B
array('i', [4, 5, 1, 2, 3])

196 | P a g e
 C
array('i', [1, 2, 3, 9, 10])
 D
Error
Explanation- The += operator concatenates two arrays of the same type.
Question 9. What is the time complexity of accessing an element in an array by index?
 A
O(n)
 B
O(log n)
 C
O(1)
 D
O(n^2)
Explanation- Accessing an element by index in an array takes constant time, O(1).
Question 10. Which of the following operations is not allowed on a Python array?
 A
Accessing an element by index
 B
Slicing
 C
Adding elements of different types
 D
Iterating through elements
Explanation- Python arrays created using the array module can only store elements of the
same type.

List Comprehension in Python




List comprehension is a way to create lists using a concise syntax. It allows us to


generate a new list by applying an expression to each item in an
existing iterable (such as a list or range). This helps us to write cleaner, more
readable code compared to traditional looping techniques.
For example, if we have a list of integers and want to create a new list containing the
square of each element, we can easily achieve this using list comprehension.

a = [2,3,4,5]

res = [val ** 2 for val in a]

print(res)

Output
[4, 9, 16, 25]

197 | P a g e
Syntax of List Comprehension
[expression for item in iterable if condition]
 expression: The transformation or value to be included in the new list.
 item: The current element taken from the iterable.
 iterable: A sequence or collection (e.g., list, tuple, set).
 if condition (optional): A filtering condition that decides whether the current item
should be included.
This syntax allows us to combine iteration, modification, and conditional filtering all in
one line.
For Loop vs. List Comprehension
The main difference is that a for loop requires multiple lines to create a new list by
iterating over items and manually adding each one. Whereas, list comprehension do
the same task in a single line, this makes the code simpler and easier to read.
Example: Let's take an example, where we want to double each number of given list
into a new list
Using a for loop:

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

# Create an empty list 'res' to store results


res = []

# Iterate over each element in list 'a'


for val in a:

# Multiply each element by 2 and append it to 'res'


res.append(val * 2)

print(res)

Output
[2, 4, 6, 8, 10]
Explanation: Create an empty list 'res' to store results and iterate over each element
in list 'a' and for each items in list 'a', multiply it by 2 and append it to 'res'
using append() method.
Using list comprehension:

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

res = [val * 2 for val in a]

print(res)

Output
[2, 4, 6, 8, 10]

198 | P a g e
Explanation: In the above list comprehension, the iterable is a list 'a', and the
expression is val * 2, which multiplies each value from the list by 2.
Conditional Statements in List Comprehension
List comprehensions can include conditional statements to filter or modify items
based on specific criteria. These conditionals help us create customized lists quickly
and making the code cleaner and more efficient.
Example: Suppose we want to filter all even list from the given list.

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

res = [val for val in a if val % 2 == 0]

print(res)

Output
[2, 4]
To learn more about filtering conditions in list comprehensions, please refer to "Python
List Comprehension Using If-Else"
Examples of list comprehension
Creating a list from a range
A simple example is creating a list of numbers from 0 to 9.

# Creates a list of numbers from 0 to 9


a = [i for i in range(10)]

print(a)

Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using nested loops


List comprehension can also be used with nested loops. Here, we generate a list of
coordinate pairs for a simple 3x3 grid.

# Creates a list of tuples representing all combinations of (x, y)


# where both x and y range from 0 to 2.
coordinates = [(x, y) for x in range(3) for y in range(3)]

print(coordinates)

Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2,
2)]

199 | P a g e
Flattening a list of lists
Suppose we have a list of lists and we want to convert it into a single list.

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

res = [val for row in mat for val in row]

print(res)

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: The line [val for row in mat for val in row] uses nested list
comprehension to iterate through each row in mat. For each row, it iterates through
each val in that row and collecting all values into a single list.

Python List Comprehension Quiz


Question 1. What is List Comprehension in Python?
 A
A method to create lists
 B
A syntax for creating a list based on an existing iterable
 C
A built-in Python function
 D
A way to append elements to a list
Explanation- List comprehension provides a concise way to create lists.
Question 2
Which symbol is used for List Comprehension in Python?
 A
<>
 B
{}
 C
[]
 D
()
Explanation- Square brackets [] are used for list comprehension.
Question 3. What will the following list comprehension output?
squares = [x**2 for x in range(5)]

 A
[0, 1, 4, 9, 16]
 B
[1, 4, 9, 16, 25]
 C
[0, 2, 4, 6, 8]
 D
[1, 3, 5, 7, 9]
200 | P a g e
Explanation- It creates a list of squares of numbers from 0 to 4.
Question 4. Which of the following statements is true about list comprehension?
 A
It can only be used for creating lists of integers
 B
It can include an optional if clause for filtering elements
 C
It cannot be used to create lists of strings
 D
It cannot be nested
Explanation- List comprehension can include conditions to filter elements.
Question 5. What is the output of the following list comprehension?
vowels = ['a', 'e', 'i', 'o', 'u']
upper_vowels = [vowel.upper() for vowel in vowels]

 A
['a', 'e', 'i', 'o', 'u']
 B
['A', 'E', 'I', 'O', 'U']
 C
['a', 'E', 'i', 'O', 'u']
 D
['A', 'e', 'I', 'o', 'U']
Explanation- It creates a list of uppercase vowels.
Question 6. What will the following list comprehension output?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]

 A
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 B
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 C
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
 D
[[1], [2], [3], [4], [5], [6], [7], [8], [9]]
Explanation- It flattens a 2D matrix into a single list.
Question 7. Which of the following is the correct syntax for a basic list comprehension in Python?
 A
{x for x in iterable}
 B
[x in iterable]
 C
(x for x in iterable)
 D
[x for x in iterable]
Explanation- List comprehensions in Python use square brackets with the syntax: [expression
for item in iterable]. The other forms represent set comprehension, generator expression, or
invalid syntax.
Question 8. What is the purpose of the if clause in list comprehension?

201 | P a g e
 A
Adds an element to the list
 B
Excludes an element from the list based on a condition
 C
Sorts the elements in the list
 D
Converts elements to uppercase
Explanation- The if clause is used to filter elements based on a condition.
Question 9. What will the following list comprehension output?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
filtered = [row[1] for row in matrix if row[1] % 2 == 0]

 A
[2, 5, 8]
 B
[1, 4, 7]
 C
[2, 4, 6, 8]
 D
[1, 2, 3]
Explanation- It extracts the second element from each row if it's even.
Question 10. What happens if you use list comprehension without assigning it to a variable?
 A
It raises a syntax error.
 B
It creates a list but doesn't store it.
 C
It modifies the original list in-place.
 D
It returns a generator object.
Explanation- List comprehension can be used to create a list without assigning it to a variable.
Question 11. What is the primary advantage of using list comprehension over traditional loops in
Python?
 A
List comprehension is more memory-efficient.
 B
List comprehension is faster.
 C
List comprehension allows complex logic.
 D
List comprehension supports parallel processing.
Explanation- List comprehension is generally faster and more concise than traditional loops.
Question 12. What is the purpose of the following list comprehension?
numbers = [1, 2, 3, 4, 5]
squared_odd_sum = [sum(x**2 for x in numbers) if sum(x for x in numbers) % 2 != 0 else x for x in
numbers]
 A
Squares all numbers in the list.
 B
Squares only odd numbers in the list.
 C

202 | P a g e
Squares the sum of odd numbers.
 D
Squares numbers based on the sum of all numbers.
Explanation- The code sums all numbers and checks if the sum is odd. If it is, it computes the
sum of squares of all numbers and assigns that value to every element of the new list (1² + 2² +
3² + 4² + 5² = 55) resulting in list = [55, 55, 55, 55, 55]
Question 13. In list comprehension, what does the expression represent?
 A
The iterable being traversed.
 B
The condition for filtering elements.
 C
The value to be included in the new list.
 D
The index of the current element.
Explanation- The expression determines what value to include in the new list.
Question 14. What is the role of the if clause in list comprehension?
 A
It sets the value of the expression.
 B
It creates a filter for elements.
 C
It is used for iteration.
 D
It reverses the order of elements.
Explanation- The if clause filters elements based on a specified condition.
Question 15. When using list comprehension, what happens if the iterable is empty?
 A
It raises a ValueError.
 B
It creates an empty list.
 C
It raises a SyntaxError.
 D
It results in an infinite loop.
Explanation- List comprehension handles an empty iterable by creating an empty list.
Question 16. What is the difference between a list comprehension and a generator expression?
 A
List comprehensions are more memory-efficient.
 B
Generator expressions are more memory-efficient.
 C
They are equivalent; there is no difference.
 D
List comprehensions are faster.
Explanation- Generator expressions are more memory-efficient as they produce values on-the-
fly.
Question 17. Explain the term "nested list comprehension."
 A
It refers to using multiple conditions in a single list comprehension.

203 | P a g e
 B
It involves using a list comprehension inside another list comprehension.
 C
It is a type of list comprehension specific to nested lists.
 D
It is an advanced feature not related to list comprehensions.
Explanation- Nested list comprehension involves using one or more list comprehensions inside
another.
Question 18. Explain the concept of filtering in list comprehension.
 A
It involves transforming elements based on a specified condition.
 B
It refers to the process of excluding elements based on a condition.
 C
It is a technique for optimizing list comprehension.
 D
It is not applicable to list comprehension.
Explanation- Filtering in list comprehension involves excluding elements that do not satisfy a
specified condition.
Question 19. What is the purpose of the following set comprehension?
words = ['python', 'list', 'comprehension']
unique_starting_letters = {word[0].upper() for word in words}
 A
Creates a list of unique starting letters of words.
 B
Creates a set of unique starting letters of words.
 C
Creates a dictionary with starting letters as keys and words as values.
 D
Counts the occurrences of each starting letter.
Explanation- This code uses set comprehension ({...}) to extract the first letter of each word,
convert it to uppercase, and store it in a set, ensuring all starting letters are unique.
Question 20. What is the purpose of the following list comprehension?
numbers = [1, -2, 3, -4, 5]
squared_positives = [x**2 if x > 0 else 0 for x in numbers]
 A
Squares all numbers.
 B
Squares only positive numbers.
 C
Squares only negative numbers.
 D
Squares numbers greater than 3.
Explanation- It uses a conditional expression to square only positive numbers.
Question 21. Can list comprehension be used with other data types besides lists?
 A
No, it can only be used with lists.
 B
Yes, it can be used with any iterable.
 C

204 | P a g e
Yes, but only with strings.
 D
No, it is limited to numerical data types.
Explanation- List comprehension can be used with any iterable, not just lists.
Question 22. How can list comprehension be used to create a list of tuples?
 A
By converting a list to a tuple after using list comprehension.
 B
By using the tuple() constructor within the list comprehension.
 C
List comprehension can only create lists, not tuples.
 D
By enclosing each element in parentheses within the list comprehension.
Explanation- The tuple() constructor can be used to create tuples within a list comprehension.
Question 23. What is the significance of the order of for clauses in nested list comprehensions?
 A
The order has no effect on the result.
 B
It determines the order of elements in the resulting list.
 C
It is not possible to have multiple for clauses in list comprehension.
 D
It only affects the readability of the code.
Explanation- The order of for clauses in nested list comprehensions affects the order of
elements in the resulting list.
Question 24. What will the following list comprehension output?
words = ['apple', 'banana', 'cherry']
word_lengths = {word: len(word) for word in words if len(word) % 2 == 0}
 A
{'apple': 5, 'banana': 6, 'cherry': 6}
 B
{'apple': 5, 'banana': 6}
 C
{'apple': 5, 'cherry': 6}
 D
{'banana': 6, 'cherry': 6}
Explanation- It creates a dictionary with words of even length and their lengths.
Question 25. In what scenarios might it be better to use traditional loops instead of list
comprehension?
 A
When the code needs to be more concise.
 B
When the logic involves complex conditions.
 C
In situations where performance is critical.
 D
List comprehension is always preferable.
Explanation- Traditional loops might be preferable when the logic involves complex conditions
that are hard to express within a list comprehension.

205 | P a g e
Python Arrays
In Python, arrays are a data structure that allows you to store multiple items of the same data type
in a single variable.
Question 1. What is the output of the following code?
from array import array
arr = array('i', [1, 2, 3, 4, 5])
print(arr[0])

 A
0
 B
1
 C
5
 D
Error
Explanation- Unlike Python’s built-in list, the array module is for homogeneous arrays (all
elements must be of the same type) hence 'i' denotes "unsigned integers" and then accessing
the first element of the array returns the value 1.
Question 2. Which of the following is the correct way to create an array in Python using the array
module?
 A
array = [1, 2, 3]
 B
array = array('i', [1, 2, 3])
 C
array = (1, 2, 3)
 D
array = {1, 2, 3}
Explanation- array module in Python is used to create an array, which is different from lists
Question 3. Which of the following methods is used to add an element to the end of an array?
 A
insert()
 B
append()
 C
extend()
 D
add()
Explanation- The append method adds an element to the end of the array.
Question 4. How to create an empty array of integers in Python using the array module?
 A
arr = array('i')
 B
arr = array('i', [])
 C
Both a and b
 D
None of the above

206 | P a g e
Explanation- Both array('i') and array('i', []) can be used to create an empty array of integers.
Question 5. What will be the output of the following code?
from array import array
arr = array('i', [1, 2, 3])
arr.insert(1, 4)
print(arr)

 A
array('i', [1, 4, 2, 3])
 B
array('i', [4, 1, 2, 3])
 C
array('i', [1, 2, 3, 4])
 D
Error
Question 6. What does the index method do in an array?
 A
Returns the last occurrence of a specified value
 B
Inserts a value at a specified position
 C
Returns the index of the first occurrence of a specified value
 D
Removes an element at a specified position
Explanation- The index method returns the index of the first occurrence of a specified value.
Question 7. What does the following code print?
from array import array
arr = array('i', [1, 2, 3])
arr[1] = 5
print(arr)

 A
array('i', [1, 2, 3])
 B
array('i', [5, 2, 3])
 C
array('i', [1, 5, 3])
 D
Error
Explanation- Assigning a new value to an element at a specific index updates the array.
Question 8. What is the result of the following code?
from array import array
arr1 = array('i', [1, 2, 3])
arr2 = array('i', [4, 5])
arr1 += arr2
print(arr1)

 A
array('i', [1, 2, 3, 4, 5])
 B
array('i', [4, 5, 1, 2, 3])
 C

207 | P a g e
array('i', [1, 2, 3, 9, 10])
 D
Error
Explanation- The += operator concatenates two arrays of the same type.
Question 9. What is the time complexity of accessing an element in an array by index?
 A
O(n)
 B
O(log n)
 C
O(1)
 D
O(n^2)
Explanation- Accessing an element by index in an array takes constant time, O(1).
Question 10. Which of the following operations is not allowed on a Python array?
 A
Accessing an element by index
 B
Slicing
 C
Adding elements of different types
 D
Iterating through elements
Explanation-Python arrays created using the array module can only store elements of the
same type.

Python Sets Quiz


Question 1. What is the output of the following program?
set1 = {1, 2, 3, 4, 4}
print(set1)
 A
{1, 2, 3}
 B
{1, 2, 3, 4}
 C
{1, 2, 3, 4, 4}
 D
Error
Explanation
Duplicate values are not allowed in sets. Hence, the output of the code shown above will be a
set containing the duplicate value only once. Hence output will be {1, 2, 3, 4}.
Question 2. What is the output of the following program?
set1 = {3, 4, 5}
set1.update([1, 2, 3])
print(set1)
 A
{1, 2, 3, 4, 5}
 B
{3, 4, 5, 1, 2, 3}

208 | P a g e
 C
{1, 2, 3, 3, 4, 5}
 D
Error
Explanation- The method update adds elements to a set.
Question 3. What is the output of the following program?
set1 = {1, 2, 3}
set2 = set1.copy()
set2.add(4)
print(set1)
 A
{1, 2, 3, 4}
 B
{1, 2, 3}
 C
Invalid Syntax
 D
Error
Explanation- In the above piece of code, set2 is barely a copy and not an alias of set1. Hence
any change made in set2 isn’t reflected in set1.
Question 4. What is the output of the following program?
set1 = {1, 2, 3}
set2 = set1.add(4)
print(set2)
 A
{1, 2, 3, 4}
 B
{1, 2, 3}
 C
Invalid Syntax
 D
None
Explanation- The add method doesn’t return anything. Hence there will be no output.
Question 5. What is the output of the following program?
set1 = {1, 2, 3}
set2 = {4, 5, 6}
print(len(set1 + set2))
 A
3
 B
6
 C
Unexpected
 D
Error
Explanation- The unsupported operand type(s) for +: ‘set’ and ‘set’.
Question 6. What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 | set2)
 A
209 | P a g e
{0, 1, 2, 3, 4, 5}
 B
{0, 1, 2, 3, 4, 5, 6, 8}
 C
{ 6, 8}
 D
None
Explanation- The "|" operator is used for union.
Question 7. What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 & set2)


 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{0, 1, 3, 5, 6, 8}
 C
{2, 4}
 D
{0, 8, 6}
Explanation- The "&" operator is used for intersection.
Question 8. What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 - set2)
 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{0, 8, 6}
 C
{2, 4}
 D
{0, 1, 3, 5, 6, 8}
Explanation- The "-" operator is used to get the difference between two iterable.
Question 9. What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 ^ set2)
 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{2, 4}
 C
{0, 8, 6}
 D
{0, 1, 3, 5, 6, 8}
Explanation- The "^" operator is used to get the Symmetric difference.
Question 10. What is the output of the following program?
210 | P a g e
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])

print(set1)
 A
{1, 2, 4, 4, 3, 3, 3, 6, 5}
 B
{1, 2, 3, 4, 5, 6}
 C
[1, 2, 3, 4, 5, 6]
 D
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Explanation- All the elements in sets must be unique.
Question 11. What is the output of the following program?
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])

print(set1)
 A
{4, 5, 6, 7, 10, 11}
 B
{4, 5, 10, 11}
 C
{4, 5, (6, 7), 10, 11}
 D
None
Explanation- The update() method accepts lists, strings, tuples as well as other sets as its
arguments. In all of these cases, duplicate elements are avoided.

211 | P a g e

You might also like