0% found this document useful (0 votes)
5 views54 pages

Python Unit 5 ( List , Tuple , Set , Dict )

This document provides an overview of Python programming concepts, including output and input statements, decision-making structures, loops, and lists. It explains the usage of print() and input() functions, various conditional statements like if, elif, and nested if, as well as loop constructs such as while and for loops. Additionally, it covers list characteristics, indexing, slicing, and basic operations on lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views54 pages

Python Unit 5 ( List , Tuple , Set , Dict )

This document provides an overview of Python programming concepts, including output and input statements, decision-making structures, loops, and lists. It explains the usage of print() and input() functions, various conditional statements like if, elif, and nested if, as well as loop constructs such as while and for loops. Additionally, it covers list characteristics, indexing, slicing, and basic operations on lists.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

PYTHON PROGRAMMING

Course Code: SEC-1


UNIT - V

Prabhudatta Giri
Department Of Computer
Science & Application
Output Statements
In Python, you can use the print() function to output statements to the console.

The print() function is a built-in function that prints the specified message to the
screen or another standard output device.

Here are some examples of how you can use the print() function to output
statements in Python.

Printing a String:
print("Hello, World!")
# Output: Hello, World!

Printing Variables:
name = "Ram"
age = 21
print("Name:", name, "Age:", age)

# Output: Name: Ram Age: 21

Printing Expressions:
x=5
y = 10
print("Sum:", x + y)

# Output : 15

Formatting Output:
name = "Hari"
age = 25
print("Name: {}, Age: {}".format(name, age))

# Output : Name: Hari, Age: 25


or using f-strings (formatted string literals, available in Python 3.6 and later):

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

# Output : Name: Hari, Age: 25


Input Statements
The input() function takes input from the user and returns it.

input() Syntax
input(Prompt)

input() Parameters
The input() function takes a single optional argument:

prompt (Optional) - a string that is written to standard output (usually screen)


without trailing newline.

input() Return Value


The input() function reads a line from the input (usually from the user), converts the
line into a string by removing the trailing newline, and returns it.

Example :
name = input("Enter your name: ")
print(name)

Output :
Enter your name: Imperial
Imperial

Type Conversion
If you need to convert the input to another data type, you can use the appropriate
type conversion function. For example, to convert the input to an integer, you can use
the int() function.

Example :
age = int(input("How old are you? "))
print("You are " + str(age) + " years old.")
# or
print("You are ",age," years old")
Decision Making in Python
There might come some situation where we need to take some decision, on that
decision further execution of the code depends.

Decision making statements decides the output or result of a program. In python we


can make decision using –

➢ If statement
➢ If -else statement
➢ Elif statement
➢ Nested If statement

if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.

Syntax
if expression:
# statement
Example :
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# we are taking an integer num and taking input dynamically
if num%2 == 0: # If the condition is true, we will enter the block
print("The Given number is an even number")
# If condition is false , nothing will we happen

if-else statement
The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
Syntax
if condition:
# if block of statements
else:
# else block of statements

Example :
# Simple Python Program to check whether a number is even or not.
num = int(input("enter the number:"))
if num%2 == 0: # If the condition is true, we will enter the block
print("The Given number is an even number")
else:
print("The Given Number is an odd number")

elif statement
The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have
any number of elif statements in our program depending upon our need.

The elif statement works like an if-else-if ladder statement in C and C++.

Syntax
if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Example :
score = int(input("Enter your score: "))

if score >= 90:


grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"

print("Your grade is:", grade)


nested if Statement
The nested if statement contains the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.

Syntax
if condition:
# Code block for condition
if nested_condition:
# Code block for nested_condition
else:
# Code block for else inside nested_condition
else:
# Code block for else
# We can write any no of if else inside any if or else block
Example :
# WAP to find greatest among 3 user defined number
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Using nested if-else to find the greatest number


if num1 >= num2:
if num1 >= num3:
greatest = num1
else:
greatest = num3
else:
if num2 >= num3:
greatest = num2
else:
greatest = num3

# Displaying the result using f string (U can use normal print)


print(f"The greatest number among {num1}, {num2}, and {num3} is {greatest}.")

Output :
Enter the first number: 13.5

Enter the second number: 32.4

Enter the third number: 7.8

The greatest number among 13.5, 32.4, and 7.8 is 32.4.


Loop in Python
In Python, a loop is a control flow statement that allows you to repeat a block of code
multiple times until a certain condition is met. Loops are essential for automating
repetitive tasks and making programs more efficient.

There are two primary types of loops in Python: for loops and while loops.

while loop
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given boolean expression is true.

Syntax
while expression:
# statement
Example :
# WAP to find sum of digit of an user defined number
num = int(input("Enter a number: "))

# Initialize sum to 0
digit_sum = 0

# Use a while loop to iterate through each digit


while num > 0:
# Extract the last digit
digit = num % 10

# Add the digit to the sum


digit_sum += digit

# Remove the last digit from the number


num = num // 10

# Print the result


print("The sum of digits is: ",digit_sum)

Output :
Enter a number: 4523
The sum of digits is: 14

Python supports having an else statement associated with a while loop statement.

If the else statement is used with a while loop, the else statement is executed when
the condition becomes false before the control shifts to the main line of execution.

Syntax
while condition:
# code to be executed inside the loop
else:
# code to be executed when the while condition becomes False
Example :
# WAP to Check Wheather a number is prime or not prime number ?
num = int(input("Enter a number: "))

# Initialize a flag to indicate whether the number is prime


is_prime = True

# Check if the number is prime


i=2
while i < num:
if num % i == 0:
is_prime = False
print(str(num) + " is not a prime number.")
break # Exit the loop if the number is not prime
i += 1
else:
if is_prime and num > 1:
print(num," is a prime number.")
else:
print(num," is not a prime number.")

Output :
Enter a number: 16
16 is not a prime number.

Output 2:
Enter a number: 17
17 is a prime number.
for loop
The for loop in Python has the ability to iterate over the items of any sequence, such
as a list, tuple or a string.

Syntax
for value in sequence:
# statements

Example :
numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total+=num
print ("Total =", total)

Output :
Total = 539
Python supports having an "else" statement associated with a "for" loop statement.

If the "else" statement is used with a "for" loop, the "else" statement is executed when
the sequence is exhausted before the control shifts to the main line of execution.

Syntax
for variable in sequence:
# code to be executed inside the loop
else:
# code to be executed when the for loop complete

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

for num in numbers:


if num == 6:
print("Number 6 found!")
break
else:
print("Number 6 not found in the list.")

Using "for" with a Range Object


Python's built-in range() function returns a range object. Python's range object is an
iterator which generates an integer with each iteration. The object contains integers
from start to stop, separated by step parameter.

Syntax
range(start, stop, step)

Parameters
• Start − Starting value of the range. Optional. Default is 0
• Stop − The range goes up to stop-1
• Step − Integers in the range increment by the step value. Option, default is 1.

Return Value
The range() function returns a range object. It can be parsed to a list sequence.
Example :
# WAP to find the sum of even number in between 1 to 20
even_sum = 0

# Iterate through the numbers from 1 to 20 using range


for num in range(1, 21):
# Check if the number is even
if num % 2 == 0:
even_sum += num

# Print the result


print("The sum of even numbers between 1 and 20 is: " ,even_sum)

Output :
The sum of even numbers between 1 and 20 is: 110

Nested Loops in Python


Python programming language allows the use of one loop inside another loop. The
following section shows a few examples to illustrate the concept.

Syntax ( Nested for loop )


for value in sequence:
for value in sequence:
# statements

Syntax ( Nested while loop )


while expression:
while expression:
# statements
# statements

Syntax ( Nested for while loop )


while condition:
# code for the outer loop

for variable in sequence:


# code for the inner loop
Loop Control Statements
Statements used to control loops and change the course of iteration are called control
statements. All the objects produced within the local scope of the loop are deleted
when execution is completed.
The primary loop control statements in Python are: break , continue and pass .

Break
The break is used to exit a loop prematurely, before its normal completion.

Example :
for i in range(1, 6):
if i == 3:
break
print(i)

Output :
1
2
In this example, the loop terminates when i is equal to 3 due to the break statement.

Continue
The continue is used to skip the rest of the loop's code and move to the next
iteration of the loop.

Example :
for i in range(1, 6):
if i == 3:
continue
print(i)

Output :
1
2
4
5

In this example, when i is equal to 3, the continue statement skips the print(i)
statement and moves to the next iteration of the loop.
Pass
The pass is a null operation; nothing happens when it executes. It is often used as a
placeholder when a statement is syntactically required but you don't want to do
anything.

Example :
for i in range(1, 4):
pass

In this example, the pass statement does nothing, and the loop runs for its specified
range without any additional action.

Quit and Exit


The quit() and exit() are functions that raise the SystemExit exception, terminating
the program.

Example :
print("Before quit()")
quit()
print("After quit()") # This line will not be executed

Output :
Before quit()

In this example, the program terminates after the quit() function is called, and the
line after quit() is not executed.

Example :
print("Before exit()")
exit()
print("After exit()") # This line will not be executed

Output :
Before exit()

The exit() function works the same way as quit(). It raises the SystemExit exception
and terminates the program. It's better to let the program naturally exit by reaching
the end of the script or function.
Lists
A list is a sequence of comma separated items, enclosed in square brackets [ ]. The
items in a Python list need not be of the same data type.

Lists in Python are identical to dynamically scaled arrays defined in other languages,
such as Array List in Java and Vector in C++.

A list can

➢ store elements of different types (integer, float, string, etc.)


➢ store duplicate elements

Syntax
List_name = [ element1, element2, element3, ........]

Example :
# List of similar elements
list1 = ["Aditya","Arbab","Debadatta","Deepak","Gopal"]

# List of dissimilar elements


list2 = ["Chinki",2114,True,13.5]

# printing the list


print(list1)
print(list2)

# printing the type of list


print(type(list1))
print(type(list2))

Output :
['Aditya', 'Arbab', 'Debadatta', 'Deepak', 'Gopal']

['Chinki', 2114, True, 13.5]

<class 'list'>

<class 'list'>
Characteristics of Lists
The characteristics of the List are as follows:

→ The lists are in order.


→ The list element can be accessed via the index.
→ The list is mutable.
→ The list element are changeable sorts.
→ The number of various elements can be stored in a list.

Access List Elements


In Python, lists are ordered and each item in a list is associated with a number. The
number is known as a list index.

The index of the first element is 0, second element is 1 and so on.

Example :
languages = ["Python", "Swift", "C++"]

# access item at index 0


print(languages[0]) # Python

# access item at index 2


print(languages[2]) # C++

Python allows negative indexing for its sequences. The index of -1 refers to the last
item, -2 to the second last item and so on.

Example :
languages = ["Python", "Swift", "C++"]

# access item at index 0


print(languages[-1]) # C++

# access item at index 2


print(languages[-3]) # Python

Note: If the specified index does not exist in a list, Python throws the IndexError
exception.
Slicing of a List
In Python, it is possible to access a portion of a list using the slicing operator : .
We can get the sub-list of the list using the slicing operator [ : ]
Syntax.
list_varible [start:stop:step]

➢ The start indicates the beginning record position of the list.


➢ The stop signifies the last record position of the list.
➢ Within a start, the step is used to skip the nth element: stop.

Example :
# Slicing the elements
list = ['Ind','Pak','Ban','Afg','Sl','Nep']

# items beginning to end


print(list[:])

# items from index 2 to index 4


print(list[2:5])

# items from start to index 4


print(list[:5])

# items from index 5 to end


print(list[5:])

# items from index 1 to index 5 with step 2


print(list[1:6:2])

Output :
['Ind', 'Pak', 'Ban', 'Afg', 'Sl', 'Nep']
['Ban', 'Afg', 'Sl']
['Ind', 'Pak', 'Ban', 'Afg', 'Sl']
['Nep']
['Pak', 'Afg', 'Nep']
List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings. The different operations of list are

1. Concatenation

2. Repetition

3. Length

4. Iteration

5. Membership

Concatenation
It concatenates the list mentioned on either side of the operator.

Example :
# concatenation of two lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)

Output :

[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]

Repetition
We can repeat a list multiple times using the repetition operator (*). The repetition
operator allows you to create a new list by repeating the elements of an existing list a
specified number of times.

Example :
# repetition of list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)

Output :
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]

Length
It is used to get the length of the list.
Example :
# length of the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)

Output :
9

Iteration
The for loop is used to iterate over the list elements.
Example :
# iteration of the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)

Output :
12
14
16
39
40
Membership
It returns true if a particular item exists in a particular list otherwise false.

Example :
# membership of the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not

print(700 in list1)
print(1040 in list1)

print(300 in list1)
print(100 in list1)

Output :
False
False
True
True

Add Elements to a List


Lists are mutable (changeable). Meaning we can add and remove elements from a
list.

Python list provides different methods to add items to a list.

1. Using append() Method :


The append() method adds an item at the end of the list.

Example :
numbers = [21, 34, 54, 12]
print("Before Append:", numbers)
# using append method
numbers.append(32)
print("After Append:", numbers)
Output :
Before Append: [21, 34, 54, 12]

After Append: [21, 34, 54, 12, 32]

2. Using extend() Method :


We use the extend() method to add all the items of an iterable (list, tuple, string,
dictionary, etc.) to the end of the list.

Example :
numbers = [1, 3, 5]
even_numbers = [4, 6, 8]

# add elements of even_numbers to the numbers list


numbers.extend(even_numbers)

print("List after append:", numbers)

Output :

List after append: [1, 3, 5, 4, 6, 8]

3. Using insert() Method :

We use the insert() method to add an element at the specified index.


Example :
numbers = [10, 30, 40]

# insert an element at index 1 (second position)


numbers.insert(1, 20)

print(numbers)

Output :
[10, 20, 30, 40]
Change List Items
Python lists are mutable. Meaning lists are changeable. And we can change items of
a list by assigning new values using the = operator.

Example :
languages = ['Python', 'Swift', 'C++']

# changing the third item to 'C'


languages[2] = 'C'

print(languages)

Output :
['Python', 'Swift', 'C']

Remove an Item From a List


1. Using del Keyword
In Python we can use the del statement to remove one or more items from a list.
Example :
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item


del languages[1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the last item


del languages[-1]
print(languages) # ['Python', 'C++', 'C', 'Java', 'Rust']

# delete the first two items


del languages[0 : 2]
print(languages) # ['C', 'Java', 'Rust']

# delete the list


del languages
print(languages) # NameError: name 'languages' is not defined
2. Using remove() Method :
We can also use the remove() method to delete a list item.
Example :
my_list = [1, 2, 3, 4, 5, 6]
# remove item 3 from the list
my_list.remove(3)
print(my_list)

Output :
[1, 2, 4, 5, 6]

3. Using pop() Method :


The pop() method removes and returns the item at the specified index. If no index is
provided, it removes and returns the last item in the list.
Example :
my_list = [1, 2, 3, 4, 5]
# pop item which index = 2 from the list
removed_item = my_list.pop(2)
print(my_list)
print("Removed item:", removed_item)

Output :
[1, 2, 4, 5]
Removed item: 3
List Methods
Python has many useful list methods that makes it really easy to work with lists.

Method Description

append() add an item to the end of the list

extend() add all the items of an iterable to the end of the list

insert() inserts an item at the specified index

remove() removes item present at the given index

pop() returns and removes item present at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the specified item in the list

sort() sort the list in ascending/descending order

reverse() reverses the item of the list

copy() returns the shallow copy of the list

join() Method:
The join() method is used to concatenate elements of an iterable (such as a list, tuple,
or string) into a single string. It takes an iterable as an argument and returns a string
in which the elements of the iterable are joined by the specified separator.

Syntax:
separator.join(iterable)

➢ separator: It is a string that separates the elements of the iterable.


➢ iterable: It can be a list, tuple, string, or any other iterable object.

Example 1: Joining elements of a list into a string:


words = ["Hello", "World", "Python"]
sentence = " ".join(words)
print(sentence)
# Output: Hello World Python
Example 2: Joining characters of a string with a separator:
word = "Python"
separator = "-"
result = separator.join(word)
print(result)
# Output: P-y-t-h-o-n

split() Method:
The split() method is used to split a string into a list of substrings based on a specified
delimiter. If no delimiter is specified, it splits the string based on whitespace characters.

Syntax:
string.split(separator, maxsplit)

➢ separator: (Optional) It is the delimiter on which the string will be split. If not
specified, the string is split at whitespace characters.
➢ maxsplit: (Optional) It specifies how many splits to do. Default value is -1, meaning
"all occurrences".

Example 1: Splitting a string using whitespace as a delimiter:


sentence = "Hello World Python"
words = sentence.split()
print(words)
# Output: ['Hello', 'World', 'Python']

Example 2: Splitting a string using a specific delimiter:


sentence = "apple,orange,banana,grape"
fruits = sentence.split(",")
print(fruits)
# Output: ['apple', 'orange', 'banana', 'grape']

Example 3: Splitting a string with a specified maximum number of splits:


sentence = "Hello,World,Python"
words = sentence.split(",", 1)
print(words)
# Output: ['Hello', 'World,Python']
Tuples
A tuple is a sequence of comma separated items, enclosed in parentheses (). The items
in a Python tuple need not be of same data type.

Features of Python Tuple


➢ Tuples are an immutable data type, meaning their elements cannot be changed
after they are generated.
➢ Each element in a tuple has a specific order that will never change because
tuples are ordered sequences.

Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated
by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer,
float, list, string, etc.).

Syntax
Creating an empty tuple
empty_tuple = ()

Creating a tuple with elements


tuple_name = (element1, element2, element3, ...)

Creating a tuple without parentheses (also creates a tuple)


tuple_name = element1, element2, element3, ...

Example :
# Creating an empty tuple
tuple0 = ()

# Creating tuples with elements


tuple1 = (1, 2, 3, 4, 5)
tuple2 = ('apple', 'banana', 'cherry')
tuple3 = (1, 'hello', 3.14)

# Creating tuples without parentheses


tuple4 = 1, 2, 3, 4, 5
tuple5 = 'a', 'b', 'c'
Accessing Tuple Elements:
Positive Indexing:
In Python, tuples are ordered sequences, and elements within a tuple are accessed
using indices. Positive indexing starts from 0 for the first element, 1 for the second
element, and so on.

Negative Indexing:
Python also supports negative indexing, where -1 represents the last element of the
tuple, -2 represents the second last element, and so on. Negative indices allow you
to access elements from the end of the tuple without knowing its length.

Example :
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50)

# Accessing elements using positive indices


print(my_tuple[0]) # Output: 10 (first element)
print(my_tuple[2]) # Output: 30 (third element)
print(my_tuple[4]) # Output: 50 (fifth element)

# Accessing elements using negative indices


print(my_tuple[-1]) # Output: 50 (last element)
print(my_tuple[-3]) # Output: 30 (third element from the end)
print(my_tuple[-5]) # Output: 10 (first element from the end)
Slicing Tuple Elements
Slicing in Python allows you to extract a portion of a sequence, such as a list, string, or
tuple. It allows you to extract a specific subset of elements from the tuple based on
their indices.

Syntax
tuple_variable [start:stop:step]

start: The index from where the slicing starts (inclusive).


stop: The index where the slicing ends (exclusive).
step: The step value determines how many indices to skip while slicing (optional).

1. Basic Slicing:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sliced_tuple = my_tuple[2:6]
print(sliced_tuple)
# Output: (3, 4, 5, 6)

2. Slicing with Step:


my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sliced_tuple = my_tuple[1:8:2]
print(sliced_tuple)
# Output: (2, 4, 6, 8)

3. Omitting Start and Stop Indices:


my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sliced_tuple = my_tuple[::2]
print(sliced_tuple)
# Output: (1, 3, 5, 7, 9)

4. Negative Indices:
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)
sliced_tuple = my_tuple[-5:-2]
print(sliced_tuple)
# Output: (5, 6, 7)
Tuple operators in Python

Concatenation Operator (+):


The + operator can be used to concatenate two or more tuples, creating a new tuple.
Example :
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(tuple3)
# Output: (1, 2, 3, 4, 5, 6)

Repetition Operator (*):


The * operator can be used to repeat a tuple multiple times.
Example :
tuple1 = (1, 2)
repeated_tuple = tuple1 * 3
print(repeated_tuple)
# Output: (1, 2, 1, 2, 1, 2)

Membership Operator (in and not in):


You can use in and not in operators to test if an element is present in the tuple.
Example :
my_tuple = (1, 2, 3, 4, 5)
print(3 in my_tuple)
# Output: True
print(6 not in my_tuple)
# Output: True

Comparison Operators (<, <=, >, >=, ==, !=):


Tuples can be compared element-wise using these operators. Comparison starts
from the first element of each tuple.
Example :
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)
print(tuple1 == tuple2)
# Output: False
print(tuple1 < tuple2)
# Output: True (comparison of the third elements since the first two are equal)

Tuple Unpacking:
Tuples can be unpacked into multiple variables. The number of variables on the left-
hand side should match the number of elements in the tuple.
Example :
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c)
# Output: 1 2 3

Built-in Functions:
Tuples support various built-in functions like len(), min(), max(), and sum().
Example :
my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple))
# Output: 5
print(min(my_tuple))
# Output: 1
print(max(my_tuple))
# Output: 5
print(sum(my_tuple))
# Output: 15

Tuple Methods
Like the list, Python Tuples is a collection of immutable objects. There are a few ways
to work with tuples in Python.

1. count() Method:
The count() method returns the number of occurrences of a specified element in the
tuple.

Syntax
tuple.count(element)
Example :
my_tuple = (1, 2, 2, 3, 4, 2)
result = my_tuple.count(2)
print(result)
# Output: 3

2. index() Method:
The index() method returns the index of the first occurrence of a specified element in
the tuple.

Syntax
tuple.index(element)

Example :
my_tuple = (1, 2, 3, 4, 5, 6)
result = my_tuple.index(3)
print(result)
# Output: 2

Iterating Through a Tuple


A for loop can be used to iterate through each tuple element.
Example :
# Python program to show how to iterate over tuple elements
language = ("Python", "Java", "JavaScript", "C","C++")
# Iterating over tuple elements using a for loop
for item in language:
print(item)

Output :
Python
Java
JavaScript
C
C++
Tuples have the following advantages over lists:
→ Triples take less time than lists do.

→ Due to tuples, the code is protected from accidental modifications. It is


desirable to store non-changing information in "tuples" instead of "records" if
a program expects it.

→ A tuple can be used as a dictionary key if it contains immutable values like


strings, numbers, or another tuple. "Lists" cannot be utilized as dictionary keys
because they are mutable.

Differences between List and Tuple in Python

Sno LIST TUPLE

1 Lists are mutable Tuples are immutable


2
The implication of iterations is Time- The implication of iterations is
consuming comparatively Faster
3
The list is better for performing
A Tuple data type is appropriate
operations, such as insertion and
for accessing the elements
deletion.

4
Tuple consumes less memory as
Lists consume more memory
compared to the list
5
Tuple does not have many built-
Lists have several built-in methods
in methods.
6
Unexpected changes and errors are
In a tuple, it is hard to take place.
more likely to occur
Set
A set is the collection of the unordered items, enclosed in curly braces {}. Each element
in the set must be unique, immutable, and the sets remove the duplicate elements.
Sets are mutable which means we can modify it after its creation.

Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}.

Syntax
set_name = {element1, element2, element3, ...}

Example :
# Creating a set of integers
my_set = {1, 2, 3, 4, 5}

# Creating a set of strings


fruits = {"apple", "banana", "orange", "mango"}

# Creating a set of mixed data types


mixed_set = {1, "hello", 3.14, (1, 2, 3)}

Example 2: Using set() method


Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
"Sunday"])
print(Days)
print(type(Days))

Output :
{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}
<class 'set'>
Note : Creating an empty set is a bit different because empty curly {} braces are also
used to create a dictionary as well. So Python provides the set() method used without
an argument to create an empty set.
Example :
# Empty curly braces will create dictionary
set3 = {}
print(type(set3))

# Empty set using set() function


set4 = set()
print(type(set4))

Output :
<class 'dict'>
<class 'set'>

Adding items to the set


Python provides the add() method and update() method which can be used to add
some particular item to the set. The add() method is used to add a single element
whereas the update() method is used to add multiple elements to the set.

1. Using the add() Method:


The add() method allows you to add a single element to the set. If the element is
already present in the set, it won't be added again (remember, sets cannot contain
duplicate elements).
Example :
# Creating an empty set
my_set = set()

# Adding elements to the set using add() method


my_set.add(1)
my_set.add(2)
my_set.add(3)

print(my_set)
# Output: {1, 2, 3}
2. Using the update() Method:
The update() method allows you to add multiple elements (from an iterable like a list,
tuple, or another set) to the set. It takes an iterable as an argument and adds its
elements to the set.

Example :
# Creating a set
my_set = {1, 2, 3}

# Adding multiple elements to the set using update() method


my_set.update([4, 5, 6])
my_set.update((7, 8, 9))
my_set.update({10, 11, 12})

print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Removing items from the set


In Python, you can remove items from a set using several methods. Here are the
common methods to remove items from a set.

1. remove() method:
The remove() method removes the specified element from the set. If the element is
not found, it raises a KeyError.

Example :
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Removing an element from the set


my_set.remove(3)
print(my_set)
# Output: {1, 2, 4, 5}

# Trying to remove a non-existing element (raises KeyError)


# my_set.remove(6)
# Output: KeyError: 6
2. discard() method:
The discard() method removes the specified element from the set if it is present. If
the element is not found, it does nothing and does not raise any error.

Example :
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Discarding an element from the set


my_set.discard(3)
print(my_set)
# Output: {1, 2, 4, 5}

# Discarding a non-existing element (no error)


my_set.discard(6)
print(my_set)
# Output: {1, 2, 4, 5}

3. pop() method:
The pop() method removes and returns an arbitrary element from the set. If the set
is empty, it raises a KeyError.
Example :
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Removing an arbitrary element from the set


removed_element = my_set.pop()
print("Removed element:", removed_element)
print(my_set)
# Output: Removed element: 1
# {2, 3, 4, 5}
4. clear() method:
The clear() method removes all elements from the set, making it an empty set.
Example :
# Creating a set
my_set = {1, 2, 3, 4, 5}

# Clearing the set


my_set.clear()
print(my_set)
# Output: set()

Set Operations
Set can be performed mathematical operation such as union, intersection, difference,
and symmetric difference. Python provides the facility to carry out these operations
with operators or methods. We describe these operations as follows.

Union ( | or union() ):
Combines two sets, removing duplicate elements.

Example :
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # or set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}

Intersection (& or intersection()):


Returns a set containing common elements of two sets.
Example :
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2 # or
set1.intersection(set2)
print(intersection_set) # Output: {3}
Difference (- or difference()):
Returns a set containing elements present in the first set but not in the second set.

Example :
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2 # or set1.difference(set2)
print(difference_set) # Output: {1, 2}

Symmetric Difference (^ or symmetric_difference()):


Returns a set containing elements that are unique to each set.

Example :
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1 ^ set2 # or
set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}

Subset (<= or issubset()):


Checks if one set is a subset of another.

Example :
set1 = {1, 2}
set2 = {1, 2, 3, 4}
is_subset = set1 <= set2 # or set1.issubset(set2)
print(is_subset) # Output: True

Superset (>= or issuperset()):


Checks if one set is a superset of another.

Example :
set1 = {1, 2, 3, 4}
set2 = {1, 2}
is_superset = set1 >= set2 # or set1.issuperset(set2)
print(is_superset) # Output: True
Disjoint Sets (isdisjoint()):
Checks if two sets have no elements in common.

Example :
set1 = {1, 2, 3}
set2 = {4, 5, 6}
is_disjoint = set1.isdisjoint(set2)
print(is_disjoint) # Output: True

FrozenSets
In Python, a frozen set is an immutable version of the built-in set data type. It is similar
to a set, but its contents cannot be changed once a frozen set is created.

Frozen set objects support many of the assets of the same operation, such as union,
intersection, Difference, and symmetric Difference. They also support operations that
do not modify the frozen set, such as len(), min(), max(), and in.

Advantages of frozenset:
1. Immutability:

• Once a frozenset is created, its elements cannot be modified. This can


be useful in situations where you want to ensure that the set remains
constant.

2. Hashability:

• frozenset is hashable and can be used as a key in dictionaries or


elements in other sets.

Creating a frozenset:
You can create a frozenset using the frozenset() constructor by passing an iterable
(e.g., a list, tuple, or another set).

Example :
frozen_set = frozenset([1, 2, 3, 4, 5])
print(frozen_set)
Dictionary
A dictionary in Python is a collection of key-value pairs. The values associated with
each key can represent any Python object. However, the keys themselves are required
to be immutable Python objects, including but not limited to strings, tuples, or
numbers.

Dictionary entries are ordered as of Python version 3.7. In Python 3.6 and before,
dictionaries are generally unordered.

The data is stored as key-value pairs using a Python dictionary.

➢ This data structure is mutable

➢ The components of dictionary were made using keys and values.

➢ Keys must only have one component.

➢ Values can be of any type, including integer, list, and tuple.

Creating the Dictionary


A dictionary is defined using curly braces {}. Each key-value pair is separated by a colon
:. Keys are usually strings, but they can be any immutable data type (e.g., numbers or
tuples). Values can be of any data type.

Syntax
Empty dictionary
my_dict = {}

Dictionary with key-value pairs


my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'…..}

Example :
Employee = {"Name": "Amit", "Age": 23, "salary":30000,"Company":"TCS"}
print(Employee)
print(type(Employee))

Output :
{'Name': 'Amit', 'Age': 23, 'salary': 30000, 'Company': 'TCS'}
<class 'dict'>
Accessing Elements:
You can access the values in a dictionary using the keys. If the key is present, you'll
get the corresponding value; otherwise, a KeyError will be raised.

Example :
# Accessing values using keys
value = my_dict['key1']
print(value) # Output: 'value1'

# Using the get() method to avoid KeyError


value = my_dict.get('key4', 'default_value')
print(value) # Output: 'default_value'

Adding Items to a Dictionary:


You can add a new key-value pair to a dictionary by simply assigning a value to a
new key.

Syntax
my_dict[new_key] = new_value

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}

# Adding a new key-value pair


my_dict['key3'] = 'value3'

print(my_dict)
# Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Updating Items in a Dictionary:


You can update the value of an existing key in a dictionary by reassigning a new
value to that key.

Syntax
my_dict[existing_key] = new_value
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}

# Updating the value of an existing key


my_dict['key1'] = 'new_value1'

print(my_dict)
# Output: {'key1': 'new_value1', 'key2': 'value2'}

Deleting Items from a Dictionary:


You can remove a key-value pair from a dictionary using the del statement or the pop()
method.

using del keyword :


The del statement is a general-purpose statement in Python used to delete items. In
the context of dictionaries, del can be used to remove a specific key along with its
associated value from the dictionary.

Syntax
del my_dict[key_to_delete]

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}

# Deleting a key-value pair using del


del my_dict['key1']

print(my_dict)
# Output: {'key2': 'value2'}

using pop() method :


The pop() method is a specific method provided by dictionaries to remove a key and
return its associated value. It allows you to specify a default value if the key is not
found, preventing a KeyError.
Syntax
value = my_dict.pop(key_to_delete)

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}

# Deleting a key-value pair using pop


value = my_dict.pop('key1')

print(my_dict)
# Output: {'key2': 'value2'}
print(value) # value1

Dictionary Functions
A function is a method that can be used on a construct to yield a value. Additionally,
the construct is unaltered. A few of the Python methods can be combined with a
Python dictionary.

len()
The len() function returns the number of key-value pairs (items) in a dictionary.
Syntax
length = len(my_dict)

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Get the number of items in the dictionary


length = len(my_dict)

print(length)
# Output: 3
keys()
The keys() function returns a view of all the keys in the dictionary.

Syntax
all_keys = my_dict.keys()

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Get a view of all keys


all_keys = my_dict.keys()

print(all_keys)
# Output: dict_keys(['key1', 'key2', 'key3'])

values()
The values() function returns a view of all the values in the dictionary.

Syntax
all_values = my_dict.values()

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Get a view of all values


all_values = my_dict.values()

print(all_values)
# Output: dict_values(['value1', 'value2', 'value3'])

items()
The items() function returns a view of all key-value pairs (items) in the dictionary as
tuples.

Syntax
all_items = my_dict.items()
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Get a view of all items


all_items = my_dict.items()

print(all_items)
# Output: dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])

clear()
The clear() function removes all items from the dictionary, making it empty.

Syntax
my_dict.clear()

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

# Clear all items from the dictionary


my_dict.clear()

print(my_dict)
# Output: {}

copy()
The copy() function creates a shallow copy of the dictionary.

Syntax
new_dict = my_dict.copy()

Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# Create a shallow copy of the dictionary
new_dict = my_dict.copy()
print(new_dict)
# Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example :
Employee = {"Name": "Gourav", "Age": 25, "salary":25000,"Company":"IServeU"}
# for loop to print all the keys of a dictionary
for x in Employee:
print(x)

# Output 1
# Name
# Age
# salary
# Company

#for loop to print all the values of the dictionary


for x in Employee:
print(Employee[x])

# Output 2
# Gourav
# 25
# 25000
# IServeU

#for loop to print the values of the dictionary by using values() method.
for x in Employee.values():
print(x)

# Output 3
# Gourav
# 25
# 25000
# IServeU

#for loop to print the items of the dictionary by using items() method
for x in Employee.items():
print(x)

# Output 4
# ('Name', 'Gourav')
# ('Age', 25)
# ('salary', 25000)
# ('Company', 'IServeU')
Functions
A Python function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application and a
high degree of code reusing.

Types of Python Functions


Python provides the following types of functions −

• Built-in functions
• User-defined functions

Built-in Functions:
Python provides a variety of built-in functions that are readily available for use.
Examples include print(), len(), input(), max(), min(), etc. These functions are built into
the Python interpreter and can be used directly without the need for import
statements.

Example:
print("Hello, Imperial")
User-Defined Functions:
We can define custom functions to provide the required functionality. Here are simple
rules to define a function in Python.

→ Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
→ Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.

→ The first statement of a function can be an optional statement; the


documentation string of the function or docstring.

→ The code block within every function starts with a colon (:) and is indented.
→ The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as
return None.

Syntax
def functionname( parameters ):
"function_docstring"
# function_body
return [expression]

Example
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return # optional

Calling a Function in Python


Once the basic structure of a function is finalized, we can execute it by calling it from
another function or directly from the Python prompt. Following is the example to call
square() function.
Example :
# Defining function
def square( num ):
""" This function computes the square of the number. """
return num**2

# Calling function
result = square(6)
print( "The square of the given number is: ", result)

Output :
The square of the given number is: 36

Function Arguments
The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Positional or required arguments
4. Variable-length arguments

Default Arguments:
Default arguments allow you to specify default values for parameters. If a value for a
parameter is not provided in the function call, the default value is used.

Example :
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "")

greet("Abhishek") # Output: Hello, Abhishek


greet("Siddarth", "Hi") # Output: Hi, Siddarth
Keyword Arguments:
Keyword arguments are passed to a function using the name of the parameter as a
keyword. This way, you can pass the arguments in a different order, making the
function call more readable and self-explanatory.
Example :
def greet(name, greeting):
print(greeting + ", " + name)

greet(greeting="Hello", name="Radha") # Output: Hello, Radha

Positional or required arguments:


Positional arguments are the most common type of function arguments in Python.
When you define a function, you specify a certain number of parameters.

When you call the function, you pass values for these parameters in the same order as
they are defined.

Example :
def greet(name, greeting):
print(greeting + ", " + name)

greet("Ayushman", "Hello") # Output: Hello, Ayushman

Variable-Length Arguments:
Python allows you to pass a variable number of arguments to a function using the
*args and **kwargs syntax.

*args is used to pass a variable number of non-keyword arguments to a function. It


allows you to pass any number of positional arguments.

Example :
def Sum_Number(*args):
total = 0
for num in args:
total += num
return total

print(Sum_Number(1, 2, 3, 4)) # Output: 10


**kwargs is used to pass a variable number of keyword arguments to a function. It
allows you to pass any number of keyword arguments.

Example :
def print_info(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)

print_info(name="Deepak", age="30", city="Bargarh")

Output:
name: Deepak
age: 30
city: Bargarh

Lambda Function
A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one
expression.

Syntax
lambda arguments : expression

Example :
mul = lambda a, b : a * b
print(mul(5, 10))

Output :
15

Example 2:
sum = lambda a, b, c : a + b + c
print(sum(5, 6, 7))

Output :
18

You might also like