Python Unit 5 ( List , Tuple , Set , Dict )
Python Unit 5 ( List , Tuple , Set , Dict )
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)
Printing Expressions:
x=5
y = 10
print("Sum:", x + y)
# Output : 15
Formatting Output:
name = "Hari"
age = 25
print("Name: {}, Age: {}".format(name, age))
input() Syntax
input(Prompt)
input() Parameters
The input() function takes a single optional argument:
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.
➢ 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: "))
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: "))
Output :
Enter the first number: 13.5
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
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: "))
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]
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
Output :
The sum of even numbers between 1 and 20 is: 110
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.
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
Syntax
List_name = [ element1, element2, element3, ........]
Example :
# List of similar elements
list1 = ["Aditya","Arbab","Debadatta","Deepak","Gopal"]
Output :
['Aditya', 'Arbab', 'Debadatta', 'Deepak', 'Gopal']
<class 'list'>
<class 'list'>
Characteristics of Lists
The characteristics of the List are as follows:
Example :
languages = ["Python", "Swift", "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++"]
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]
Example :
# Slicing the elements
list = ['Ind','Pak','Ban','Afg','Sl','Nep']
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 :
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
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]
Example :
numbers = [1, 3, 5]
even_numbers = [4, 6, 8]
Output :
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++']
print(languages)
Output :
['Python', 'Swift', 'C']
Output :
[1, 2, 4, 5, 6]
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
extend() add all the items of an iterable to the end 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)
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".
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 = ()
Example :
# Creating an empty tuple
tuple0 = ()
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)
Syntax
tuple_variable [start:stop:step]
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)
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
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
Output :
Python
Java
JavaScript
C
C++
Tuples have the following advantages over lists:
→ Triples take less time than lists do.
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}
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))
Output :
<class 'dict'>
<class 'set'>
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}
print(my_set)
# Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
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}
Example :
# Creating a set
my_set = {1, 2, 3, 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}
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}
Example :
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2 # or set1.difference(set2)
print(difference_set) # Output: {1, 2}
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}
Example :
set1 = {1, 2}
set2 = {1, 2, 3, 4}
is_subset = set1 <= set2 # or set1.issubset(set2)
print(is_subset) # Output: True
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:
2. Hashability:
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.
Syntax
Empty dictionary
my_dict = {}
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'
Syntax
my_dict[new_key] = new_value
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict)
# Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Syntax
my_dict[existing_key] = new_value
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict)
# Output: {'key1': 'new_value1', 'key2': 'value2'}
Syntax
del my_dict[key_to_delete]
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
print(my_dict)
# Output: {'key2': 'value2'}
Example :
# Original dictionary
my_dict = {'key1': 'value1', 'key2': 'value2'}
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'}
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'}
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'}
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'}
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'}
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
# 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.
• 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 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 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 + "")
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)
Variable-Length Arguments:
Python allows you to pass a variable number of arguments to a function using the
*args and **kwargs syntax.
Example :
def Sum_Number(*args):
total = 0
for num in args:
total += num
return total
Example :
def print_info(**kwargs):
for key, value in kwargs.items():
print(key + ": " + value)
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