Unit I
Unit I
INTRODUCTION TO PYTHON:
Python is a programming language that is interpreted, object-oriented, and considered to be high-level
too. Python is one of the easiest yet most useful programming languages which is widely used in the
software industry. People use Python for Competitive Programming, Web Development, and creating
software. Due to its easiest syntax, it is recommended for beginners who are new to the software
engineering field. Its demand is growing at a very rapid pace due to its vast use cases in Modern
Technological fields like Data Science, Machine learning, and Automation Tasks. For many years
now, it has been ranked among the top Programming languages.
HISTORY OF PYTHON
Python was created in 1980s by Guido van Rossum. During his research at the National Research
Institute for Mathematics and Computer Science in the Netherlands, he created Python – a super easy
programming language in terms of reading and usage. The first ever version was released in the year
1991 which had only a few built-in data types and basic functionality.
Later, when it gained popularity among scientists for numerical computations and data analysis, in
1994, Python 1.0 was released with extra features like map, lambda, and filter functions. After that
adding new functionalities and releasing newer versions of Python came into fashion.
Python 1.5 released in 1997
Python 2.0 released in 2000
Python 3.0 in 2008 brought newer functionalities
The latest version of Python, Python 3.11 was released in 2022.
Newer functionalities being added to Python makes it more beneficial for developers and improved its
performance. In recent years, Python has gained a lot of popularity and is a highly demanding
programming language. It has spread its demand in various fields which includes machine learning,
artificial intelligence, data analysis, web development, and many more giving you a high-paying
job.
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.
2
7. Community Support: Python has a large, active community that continuously contributes
resources, libraries and tools, making it easier to find help or solutions.
ADVANTAGES AND DISADVANTAGES OF PYTHON
Every programming language comes with benefits and limitations as well. These benefits and
limitations can be treated as advantages and disadvantages. Python also has a few disadvantages over
many advantages. Let’s discuss each here:
Advantages of Python:
Easy to learn, read, and understand
Versatile and open-source
Improves productivity
Supports libraries
Huge library
Strong community
Interpreted language
Disadvantages of Python:
Restrictions in design
Memory inefficient
Weak mobile computing
Runtime errors
Slow execution speed
USES AND APPLICATIONS OF PYTHON
Python being so popular and so technologically advanced has multiple use cases and has real-life
applications. Some of the most common Python applications which are very common are discussed
below.
3
1. Web Development
Developers prefer Python for web Development, due to its easy and feature-rich framework. They can
create Dynamic websites with the best user experience using Python frameworks. Some of the
frameworks are -Django, for Backend development and Flask, for Frontend development. Most
internet companies, today are using Python framework as their core technology, because this is not
only easy to implement but is highly scalable and efficient. Web development is one of the top
Applications of Python, which is widely used across the industry to create highly efficient websites.
2. Data Science
4
Data scientists can build powerful AI models using Python snippets. Due to its easily understandable
feature, it allows developers to write complex algorithms. Data Science is used to create models and
neural networks which can learn like human brains but are much faster than a single brain. It is used
to extract patterns from past data and help organizations take their decisions. Also, companies use this
field to make their future investments.
3. Web Scrapping and Automation
You can also automate your tasks using Python with libraries like BeautifulSoup, pandas, matplotlib,
etc. for scraping and web automation. Businesses use AI bots as customer support to cater to the
needs of the customers, it not only saves their money but also proved to be providing a better
customer experience. Web scrapping helps the business in analyzing their data and other competitors’
data to increase their share in the market. It will help the organizations, make their data organize and
scale business by finding patterns from the scrapped data.
5
4. CAD
You can also use Python to work on CAD (computer-aided designs) designs, to create 2D and 3D
models digitally. There is dedicated CAD software available in the market, but you can also develop
CAD applications using Python also. You can develop a Python-based CAD application according to
your customizability and complexity, depending on your project. Using Python for CAD development
allows easy deployment and integration across cross-platforms.
5. Artificial Intelligence and Machine Learning
Using libraries like Pandas, and TensorFlow, experts can work on data analysis and machine
learning applications for statistical analysis, data manipulation, etc. Python is one of the most used
Programming languages in this field. It is worth saying that Python is the language of AI and ML.
Python has contributed a lot to this field with its huge collection of libraries and large community
support. Also, the field of Artificial intelligence and Machine learning is exponentially evolving,
hence the use of Python is also going to increase a lot.
6. Game Development
Python is one of the most popular programming languages today, known for its simplicity, extensive
features and library support. Its clean and straightforward syntax makes it beginner-friendly, while its
powerful libraries and frameworks makes it perfect for developers. Python is:
6
Output
Hello World
INDENTATION IN PYTHON
Python Indentation refers to the use of whitespace (spaces or tabs) at the beginning of code line. It is
used to define the code blocks. Indentation is crucial in Python because, unlike many other
programming languages that use braces "{}" to define blocks, Python uses indentation. It improves
the readability of Python code, but on other hand it became difficult to rectify indentation errors. Even
one extra or less space can leads to indentation error.
if 10 > 5:
print("This is true!")
print("I am tab indentation")
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.
7
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored
in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals or characters in these variables.
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the
= operator is the value stored in the variable.
For example –
a= 100 # An integer assignment
b = 1000.0 # A floating point
c = "John" # A string
print (a)
print (b)
print (c)
100
1000.0
John
Multiple Assignment:
For example : a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables.
For example –
a,b,c = 1,2,"mrcet“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable
8
Output Variables:
The Python print statement is often used to output variables. Variables do not need to be declared
with any particular type and can even change type after they have been set
x=5 # x is of type int
x = "mrcet " # x is now of type
str print(x)
Output: mrcet
To combine both text and a variable, Python uses the “+” character:
Example
x = "awesome"
print("Python is " + x)
Output
Python is awesome
You can also use the + character to add a variable to another variable:
Example
x = "Python is
" y = "awesome"
z = x + y print(z)
Output:
Python is awesome
PYTHON IDENTIFIERS
In Python, identifiers are unique names that are assigned to variables, functions, classes, and other
entities. They are used to uniquely identify the entity within the program. They should start with a
letter (a-z, A-Z) or an underscore "_" and can be followed by letters, numbers, or underscores.
In the below example "first_name" is an identifier that store string value.
first_name = "Ram"
For naming of an identifier we have to follows some rules given below:
Identifiers can be composed of alphabets (either uppercase or lowercase), numbers (0-9), and
the underscore character (_). They shouldn't include any special characters or spaces.
The starting character of an identifier must be an alphabet or an underscore.
Within a specific scope or namespace, each identifier should have a distinct name to avoid
conflicts. However, different scopes can have identifiers with the same name without
interference.
9
PYTHON KEYWORDS
Keywords in Python are reserved words that have special meanings and serve specific purposes in
the language syntax. They cannot be used as identifiers (names for variables, functions, classes,
etc.). For instance, "for", "while", "if", and "else" are keywords and cannot be used as identifiers.
Below is the list of keywords in Python:
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Escape Sequence
Python Escape Sequence is a combination of characters (usually prefixed with an escape character),
that has a non-literal character interpretation such that, the character’s sequences which are considered
as an escape sequence have a meaning other than the literal characters contained therein. Most
Programming languages use a backslash \ as an escape character. This character is used as an escape
sequence initiator, any character (one or more) following this is interpreted as an escape sequence. If
an escape sequence is designated to a Non-Printable Character or a Control Code, then the sequence is
called a control character.
List of Escape Sequence in Python
Escape
Character Meaning
\’ Single quote
\” Double quote
\\ backslash
\n New line
\r Carriage Return
\t Horizontal tab
\b Backspace
10
Escape
Character Meaning
\f form feed
\v vertical tab
\0 Null character
COMMENTS IN PYTHON
Comments in Python are statements written within the code. They are meant to explain, clarify, or
give context about specific parts of the code. The purpose of comments is to explain the working of a
code, they have no impact on the execution or outcome of a program.
Python Single Line Comment
Single line comments are preceded by the "#" symbol. Everything after this symbol on the same line
is considered a comment.
first_name = "Reddy"
last_name = "Anna" # assign last name
Output
11
Reddy Anna
Python Multi-line Comment
Python doesn't have a specific syntax for multi-line comments. However, programmers often use
multiple single-line comments, one after the other, or sometimes triple quotes (either ''' or """), even
though they're technically string literals. Below is the example of multiline comment.
'''
Multi Line comment.
Code will print name.
'''
f_name = "Alen"
print(f_name)
Multiple Line Statements
Writing a long statement in a code is not feasible or readable. Breaking a long line of code into
multiple lines makes is more readable.
Using Backslashes (\)
In Python, you can break a statement into multiple lines using the backslash (\). This method is useful,
especially when we are working with strings or mathematical operations.
sentence = "This is a very long sentence that we want to " \
"split over multiple lines for better readability."
print(sentence)
# For mathematical operations
total = 1 + 2 + 3 + \
4+5+6+\
7+8+9
print(total)
Output
This is a very long sentence that we want to split over multiple lines for better readability.
45
DataTypes
This code assigns variable ‘x’ different values of few Python data types – int, float, list, set 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")
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
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)
Output
Welcome to the Geeks World
<class 'str'>
e
l
d
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 = []
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
15
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])
Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
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
t1 = ()
t2 = ('Geeks', 'For')
print("\nTuple with the use of String: ", t2)
Output
Tuple with the use of String: ('Geeks', 'For')
16
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.
t1 = tuple([1, 2, 3, 4, 5])
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.
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.
17
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
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)
Output
{'Geeks', 'For'}
Geeks For True
18
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'}
Output
For
19
Geeks
-------------------------------------------------------Advanced Data
types-----------------------------------------
Python String
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"
Output
f
GfGG
In this example, s holds the value “GfG” and is defined as a string.
Creating a String
Accessing characters in Python String
String Immutability
Deleting a String
Updating a String
Common String Methods
Concatenating and Repeating Strings
Formatting Strings
Creating a String
Strings can be created using either single (‘) or double (“) quotes.
s1 = 'GfG'
s2 = "GfG"
print(s1)
print(s2)
20
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
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.
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"
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"
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"
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"
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"
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
Output
13
24
upper() and lower(): upper() method converts all characters to uppercase. lower() method converts
all characters to lowercase.
s = "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 "
s = "Python is fun"
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)
25
Output
Hello World
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
26
False
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.
Python List
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.
a = [10, 20, 15]
print(a)
Output
10
[10, 15, 11]
Creating a List
Accessing List Elements
Adding Elements into List
Updating Elements into List
Removing Elements from List
Iterating Over Lists
Nested Lists in Python
Python List Operation Programs
Basic Example on Python List
Creating a List
27
# List of strings
b = ['apple', 'banana', 'cherry']
print(a)
print(b)
print(c)
Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
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
28
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]
Output
10
50
Adding Elements into List
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 = []
print("After append(10):", a)
# Inserting 5 at index 0
a.insert(0, 5)
print("After insert(0, 5):", 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]
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]
a.remove(30)
print("After remove(30):", 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']
Output
apple
banana
cherry
To learn various other methods, please refer to iterating over lists.
Nested Lists in Python
31
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],
[7, 8, 9]
]
Output
6
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:
# Creating an empty Tuple
tup = ()
print(tup)
# Using String
tup = ('Geeks', 'For')
print(tup)
# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))
32
Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Let’s understand tuple in detail:
Creating a Tuple
Python Tuple Operations
Accessing of Tuples
Concatenation of Tuples
Slicing of Tuple
Deleting a Tuple
Tuple Built-In Methods
Tuple Built-In Functions
Tuples VS Lists
Tuples Programs
Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)
Python Tuple Operations
Below are the Python tuple operations.
Accessing of Python Tuples
Concatenation of Tuples
Slicing of Tuple
Deleting a Tuple
Accessing of Tuples
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.
34
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])
# Tuple unpacking
tup = ("Geeks", "For", "Geeks")
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.
35
tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')
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.
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.
# Deleting a Tuple
tup = (0, 1, 2, 3, 4)
del tup
print(tup)
Tuple Built-In Methods
Tuples support only a few methods due to their immutable nature. The two most commonly used
methods are count() and index()
Built-in-
Method Description
Find in the tuple and returns the index of the given value where it’s
index( )
available
return true if any element of the tuple is true. if tuple is empty, return
any() false
sorted() input elements in the tuple and return a new sorted list
Tuples VS Lists
Similarities Differences
Methods that can be used for we generally use ‘tuples’ for heterogeneous (different) data
both lists and tuples: types and ‘lists’ for homogeneous (similar) data types.
38
Similarities Differences
count(), Index()
Tuples can be stored in lists. Iterating through a ‘tuple’ is faster than in a ‘list’.
Lists can be stored in tuples. ‘Lists’ are mutable whereas ‘tuples’ are immutable.
Both ‘tuples’ and ‘lists’ can be Tuples that contain immutable elements can be used as a key for
nested. a dictionary.
Python Sets
Python set is an unordered collection of multiple items having different datatypes. In Python, sets are
mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and
can change.
Creating a Set in Python
In Python, the most basic and efficient method for creating a set is using curly braces.
Example:
set1 = {1, 2, 3, 4}
print(set1)
Output
{1, 2, 3, 4}
Using the set() function
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’.
Note: A Python set cannot have mutable elements like a list or dictionary, as it is immutable.
Example:
# Creating a Set
set1 = set()
print(set1)
set1 = set("GeeksForGeeks")
print(set1)
39
Output
set()
{'e', 'r', 'o', 'k', 'G', 's', 'F'}
{'For', 'Geeks'}
{'for', 'Geeks'}
{'for', 'Geeks'}
Time complexity: O(n), where n is the length of the input string, list, tuple or dictionary.
Auxiliary space: O(n), where n is the length of the input string, list, tuple or dictionary.
Unordered, Unindexed and Mutability
In set, the order of elements is not guaranteed to be the same as the order in which they were added.
The output could vary each time we run the program. Also the duplicate items entered are removed by
itself.
Sets do not support indexing. Trying to access an element by index (set[0]) raises a TypeError.
We can add elements to the set using add(). We can remove elements from the set using remove(). The
set changes after these operations, demonstrating its mutability. However, we cannot changes its items
directly.
Example:
# Creating a set
set1 = {3, 1, 4, 1, 5, 9, 2}
Output
{1, 2, 3, 4, 5, 9}
'set' object is not subscriptable
Adding Elements to a Set in Python
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}
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:
41
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
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)
print("Error:", e)
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)
Output
1
43
{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)
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)
44
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.
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.
45
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
intersection_update() Updates the set with the intersection of itself and another
46
Function Description
Dictionaries in Python
A 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
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces,
separated by a ‘comma’.
# create dictionary using { }
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
Output
Alice
Alice
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
48
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}
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}
Output
1
2
age
Geeks
For
22
50
1: Geeks
2: For
age: 22
Read in detail – Ways to Iterating Over a Dictionary
Nested Dictionaries
print(d)
Lab Programs:
a=int(input("Enter a value"));
b=int(input("Enter b value"));
print("Addition of a and b",a+b);
print("Subtraction of a and b",a-b);
print("Multiplication of a and b ",a*b);
print("Division of a and b",a/b);
print("Remainder of a and b",a%b);
print("exponent of a and b",a**b);
print("floor division of a and b",a//b);
3.#Write a program to create,concatenate and print a string and accessing sub string from a given
string.
s1=input("enter first string:");
s2=input("Enter second string:");
print("first string is :", s1);
print("second string is :",s2);
print("concatenation of two strings:", s1+s2);
print("substring of given string:", s1[1:4]);
4.# Write a python script to print the current date in the following format saturday february 22
04:26:23 IST 2025.
import time;
ltime=time.localtime();
print(time.strftime("%a%b%d%H:%M:%S%Z%Y",ltime));
52
'''
%a: Abbreviated weekday name
%b: Abbreviated month name
%d: day of the month as a decimal number[01,31]
%H: Hour (24-hour clock as a decimal number[00,23]
%M:Minute as a decimal number[00,59]
%S:second as a decimal number[00,61]
%Z:Time zone name(no characters if no time zone exists)
%y:Year with century as a decimal number.'''