Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

chapter 3 python

The document provides an overview of Python Lists and Tuples, detailing their characteristics, creation methods, and operations such as accessing elements, slicing, and modifying lists. It explains how to add, remove, and check membership of elements within lists, as well as the immutability of tuples. Examples and outputs are included to illustrate the concepts discussed.

Uploaded by

Kishor Dongare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

chapter 3 python

The document provides an overview of Python Lists and Tuples, detailing their characteristics, creation methods, and operations such as accessing elements, slicing, and modifying lists. It explains how to add, remove, and check membership of elements within lists, as well as the immutability of tuples. Examples and outputs are included to illustrate the concepts discussed.

Uploaded by

Kishor Dongare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Python Programming

Prof. K.D.Dongare
Python Programming

SHREE KRUSHNA ENGG CLASSES

Lists

 Python Lists are just like dynamically sized arrays, declared in other
languages.
 The list is a sequence data type which is used to store the collection of
data.
 A single list may contain Data Types like Integers, Strings, as well as
Objects.

Example:

Var = ["Shree", "Krushna"]


print(Var)

Output:

["Shree", "Krushna"]

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

# List of strings
b = ['RAJ', 'RAVI', 'RAM']

# Mixed data types


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

Prof. K.D.Dongare
Python Programming

 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 mutable type of List is
 The rundowns are changeable sorts.
 The number of various elements can be stored in a list.

Prof. K.D.Dongare
Python Programming

 Creating a List in Python

 Lists in Python can be created by just placing the sequence inside the
square brackets[].

 A list doesn’t need a built-in function for its creation of a list.

Example:

# Python program to demonstrate Creation of List

# Creating a List
List = [] # Creating a Blanck List
print("Blank List: ")
print(List)

# Creating a List of numbers


List = [10, 20, 14]
print("\nList of numbers: ")
print(List)

# Creating a List of strings and accessing using index


List = ["Krushna", "Classes"]
print("\n List Items: ")
print(List[0])
print(List[2])

Prof. K.D.Dongare
Python Programming

Output:

Blank List:
[]

List of numbers:
[10, 20, 14]

List Items:
Krushna
Classes

Prof. K.D.Dongare
Python Programming

 Accessing elements from the List


 In order to access the list items refer to the index number. Use the
index operator [ ] to access an item in a list.
 The index must be an integer. Nested lists are accessed using nested
indexing.

Example:

# Python program to demonstrate accessing of element from


list

# Creating a List with the use of multiple values


List = ["Krushna", "Classes"]

# accessing a element from the list using index number


print("Accessing a element from the list")

Prof. K.D.Dongare
Python Programming

Output:

Accessing a element from the


list Krushna

Ex1

list1=[15,25,3,5.3,"ravi",7249495353,"Abc",0.2]
print(list1)
print(list1[0])
print(list1[5])
print(list1[2:])

print(list1[-1])

print(list1[::-1])

output

[15, 25, 3, 5.3, 'ravi', 7249495353, 'Abc', 0.2]

15

7249495353

[3, 5.3, 'ravi', 7249495353, 'Abc', 0.2]

0.2

[0.2, 'Abc', 7249495353, 'ravi', 5.3, 3, 25, 15]

We can also iterate through index number by using loop

Prof. K.D.Dongare
Python Programming

EX2

#iterating through list using for loop


list=[10,25.66,"raj",144,200]
print("List of element are")
i=0
for i in list:
print ("element at index", i)

output

List of element are

element at index 10

element at index 25.66

element at index raj

element at index 144

element at index 200

EX3

#Accessing List Elements


a = [10, 20, 30, 40, 50]
# Access first element
print(a[0])
# Access last element
print(a[-1])

Output

10

50

Prof. K.D.Dongare
Python Programming

Ex4

#iterating through list using for loop


a = [10, 20, 30, 40, 50]
print("list element are")
i=0
while i<a.__len__():
print("at index",i,"element is:",a[i])
i=i+1

Output
list element are
at index 0 element is: 10
at index 1 element is: 20
at index 2 element is: 30
at index 3 element is: 40
at index 4 element is: 50

Prof. K.D.Dongare
Python Programming

 Slicing of a List
 We can get substrings and sub lists using a slice. In Python List, there
are multiple ways to print the whole list with all the elements, but to
print a specific range of elements from the list, we use the Slice
operation.
 Slice operation is performed on Lists with the use of a colon(:).
To print elements from beginning to a range use:

[: Index]

a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]
print(a[:4])

To print elements from a specific Index till the end use

[Index:]

a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]
print(a[2:])
To print the whole list in reverse order, use

[::-1]

a = [1, 2, 3, 4, 5, 7 , 9, 6, 8]

rev = a[::-3]

Prof. K.D.Dongare
Python Programming

 Adding Elements to a Python List

Method 1: Using insert() method

Append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used.
Example:

# Python program to demonstrate


# Addition of elements in a List

# Creating a List
List = [1,2,3,4]
print("Initial List: ")
print(List)

# Addition of Element at specific Position


# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Krushna')
print("\nList after performing Insert Operation: ")
print(List)

Prof. K.D.Dongare
Python Programming

Output:

Initial List:
[1, 2, 3, 4]

List after performing Insert Operation:


['Krushna', 1, 2, 3, 12, 4]

Method 2: Using append() method

Elements can be added to the List by using the built-in append() function.
Only one element at a time can be added to the list by using the append()
method, for the addition of multiple elements with the append() method,
loops are used.
Example:
# Python program to demonstrate Addition of elements in a List
# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Element in the List


List.append(1)
List.append(2)
List.append(4)
print("\nList after Addition of Three elements: ")
print(List)

Prof. K.D.Dongare
Python Programming

Output:

Initial blank List:


[]

List after Addition of Three elements:


[1, 2, 4]

Prof. K.D.DONGARE
Python Programming

Extend: -
This function adds element of parameter list with invoking List
its syntax is:- list1 name .extend(list 2 name)

In Python, extend() method is used to add items from one list to the end of
another list. This method modifies the original list by appending all items from
the given iterable.

Using extend() method is easy and efficient way to merge two lists or add multiple
elements at once.

Let’s look at a simple example of the extend() method.

a = [1, 2, 3]

b = [4, 5]

# Using extend() to add elements of b to a

a.extend(b)

print(a)

Output

[1, 2, 3, 4, 5]

How To Find the Length of a List in Python

The length of a list refers to the number of elements in the list. There are several
methods to determine the length of a list in Python. In this article, we’ll explore
different methods to find the length of a list. The simplest and most common way
to do this is by using the len() function.

Example Using len()

The len() function is the simplest and most efficient way to find the length of a list
in Python. It’s an inbuilt function that can be used on any sequence or collection,
including lists.

a = [1, 2, 3, 4, 5]
length = len(a)
print(length)
Output
5
Prof. K.D.DONGARE
Python Programming

If we want to find the length of list without using any inbuilt function
than we can consider this method
a = [1, 2, 3, 4, 5]
# Initialize a counter to zero
count = 0
# Loop through each element in the list
for val in a:
# Increment the counter for each element
count += 1
print(count)
Using length_hint()
The length_hint() function from the operator module provides an
estimated length (not a guaranteed accurate count) of an iterable. This
method is not typically used in regular code where len() is applicable.
from operator import length_hint
a = [1, 2, 3, 4, 5]
length = length_hint(a)
print(length)
Output
5

Prof. K.D.DONGARE
Python Programming

Delete or remove Element from list


Ex1
list = ["apple", "banana", "cherry"]
list.remove("banana")
print(list)
OUTPUT
['apple', 'cherry']
Ex2
If there are more than one item with the specified value,
the remove() method removes the first occurrence:
list = ["apple", "banana", "cherry", "banana", "kiwi"]
list.remove("banana")
print(list)
OUTPUT
['apple', 'cherry', 'banana', 'kiwi']
Remove Specified Index
The pop() method removes the specified index.
Ex.
Remove the second item:
list = ["apple", "banana", "cherry"]
list.pop(1)
print(list)
OUTPUT
['apple', 'cherry']

Prof. K.D.DONGARE
Python Programming

If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
list = ["apple", "banana", "cherry"]
list.pop()
print(list)
Output
['apple', 'banana']
The del keyword also removes the specified index:
Ex to Remove the first item:
list = ["apple", "banana", "cherry"]
del list[0]
print(list)
['banana', 'cherry']
The del keyword can also delete the list completely.
Exp. To Delete the entire list:
list = ["apple", "banana", "cherry"]
del list
Clear the List
The clear() method empties the list.
The list still remains, but it has no content.
Example to Clear the list content:
list = ["apple", "banana", "cherry"]
list.clear()
print(list)

Prof. K.D.DONGARE
Python Programming

Membership operators are used to test


if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the object

not in Returns True if a sequence with the x not in


specified value is not present in the y
object

Python IN Operator
The in operator is used to check if a character/substring/element exists
in a sequence or not. Evaluate to True if it finds the specified element in a
sequence otherwise False.
# initialized some sequences
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}
# using membership 'in' operator
# checking an integer in a list
print(2 in list1)
# checking a character in a string
print('O' in str1)
# checking for a key in a dictionary
print(3 in dict1)
Output
Prof. K.D.DONGARE
Python Programming

True
False
True

operators.contains() Method

Prof. K.D.DONGARE
Python Programming

An alternative to Membership ‘in’ operator is the contains() function.


This function is part of the Operator module in Python. The function take
two arguments, the first is the sequence and the second is the value that
is to be checked.
Syntax: operator.contains(sequence, value)
Example: In this code we have initialized a list, string, set, dictionary and
a tuple. Then we use operator module’s contain() function to check if the
element occurs in the corresponding sequences or not.
import operator
# using operator.contain()
# checking an integer in a list
print(operator.contains([1, 2, 3, 4, 5], 2))
# checking a character in a string
print(operator.contains("Hello World", 'O'))
# checking an integer in aset
print(operator.contains({1, 2, 3, 4, 5}, 6))
# checking for a key in a dictionary
print(operator.contains({1: "Geeks", 2:"for", 3:"geeks"}, 3))
# checking for an integer in a tuple
print(operator.contains((1, 2, 3, 4, 5), 9))
Output
True
False
False
True
False
Python IS Operator
Prof. K.D.DONGARE
Python Programming

The is operator evaluates to True if the variables on either side of the


operator point to the same object in the memory and false otherwise.
# Python program to illustrate the use # of 'is' identity operator
num1 = 5
num2 = 5
a = [1, 2, 3]
b = [1, 2, 3]
c=a
s1 = "hello world"
s2 = "hello world"
# using 'is' identity operator on different datatypes
print(num1 is num2)
print(a is b)
print(a is c)
print(s1 is s2)
print(s1 is s2)

Output
True
False
True
True
True

Python IS NOT Operator


Prof. K.D.DONGARE
Python Programming

The is not operator evaluates True if both variables on the either side of
the operator are not the same object in the memory location otherwise it
evaluates False.
# Python program to illustrate the use # of 'is' identity operator
num1 = 5
num2 = 5
a = [1, 2, 3]
b = [1, 2, 3]
c=a
s1 = "hello world"
s2 = "hello world"
# using 'is not' identity operator on different datatypes
print(num1 is not num2)
print(a is not b)
print(a is not c)
print(s1 is not s2)
print(s1 is not s1)

Output
False
True
False
False
False

SHREE KRUSHNA ENGG CLASSES

Prof. K.D.DONGARE
Python Programming

Tuples

 Python Tuple is a collection of objects separated by commas.

 In some ways, a tuple is similar to a Python list in terms of indexing, nested


objects, and repetition but the main difference between both is Python
tuple is immutable, unlike the Python list which is mutable.

 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.

 Forming a Tuple:
 All the objects-also known as "elements"-must be separated by a comma,
enclosed in parenthesis ().
 Although parentheses are not required, they are recommended.
 Any number of items, including those with various data types (dictionary,
string, float, list, etc.), can be contained in a tuple.

Example:

# Python program to show how to create a tuple


# Creating an empty tuple
empty_tuple = ()
print("Empty tuple: ", empty_tuple)

# Creating tuple having integers


int_tuple = (4, 6, 8, 10, 12, 14)

Prof. K.D.DONGARE
Python Programming

print("Tuple with integers: ", int_tuple)

# Creating a tuple having objects of different data types


mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)

# Creating a nested tuple


nested_tuple = ("Python", {4, 5, 6, 2, 8,2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)

Output:

Empty tuple: ()
Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))

 What is Immutable in Tuples?


 Tuples in Python are similar to Python lists but not entirely.
 Tuples are immutable and ordered and allow duplicate values.

Accessing Values in Python Tuples

 Tuples in Python provide two ways by which we can access the


elements of a tuple.

 Python Access Tuple using a Positive Index

Using square brackets we can get the values from tuples in Python.

Prof. K.D.DONGARE
Python Programming

Example:

var = ("Krushna", "Classes")

print("Value in Var[0] = ", var[0])


print("Value in Var[1] = ", var[1])

Output:

Value in Var[0] = Krushna

Value in Var[1] = Classes

 Access Tuple using Negative Index

In the above methods, we use the positive index to access the value in
Python, and here we will use the negative index within [].

Example:
var = (1, 2, 3)
print("Value in Var[-1] = ", var[-1])
print("Value in Var[-2] = ", var[-2])
print("Value in Var[-3] = ", var[-3])

Output:

Value in Var[-1] = 3
Value in Var[-2] = 2
Value in Var[-3] =
1

Prof. K.D.DONGARE
Python Programming

 Tuples in a loop

We can also create a tuple with a single element in it using loops.


Example:
# python code for creating tuples in a loop
tup = ('Krushna',)

# Number of time loop runs


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

Output:

((' Krushna',),)
(((' Krushna',),),)
((((' Krushna',),),),)
(((((' Krushna',),),),),)
((((((' Krushna',),),),),),)

 Advantages of Tuples
 Tuples 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.

Prof. K.D.DONGARE
Python Programming

 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.

Loop Through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
tuple = ("apple", "banana", "cherry")
for x in tuple:
print(x)

Python slice() Function

Definition and Usage


The slice() function returns a slice object.
A slice object is used to specify how to slice a sequence. You can specify
where to start the slicing, and where to end. You can also specify the step,
which allows you to e.g. slice only every other item.

Syntax
slice(start, end, step)
Parameter Values
Paramete Description
r

Start Optional. An integer number specifying at which


position to start the slicing. Default is 0

End An integer number specifying at which position to


end the slicing

Step Optional. An integer number specifying the step of


the slicing. Default is 1

Prof. K.D.DONGARE
Python Programming

Indexing Tuples
In Python, every tuple with elements has a position or index. Each element
of the tuple can be accessed or manipulated by using the index number.
They are two types of indexing −
 Positive Indexing

 Negative Indexing

Positive Indexing
In positive the first element of the tuple is at an index of 0 and the following
elements are at +1 and as follows.
In the below figure, we can see how an element in the tuple is associated with
its index or position.

Ex pf positive indexing
tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(3))
print(tuple(7))

Output
The above code produces the following results
7
4

Prof. K.D.DONGARE
Python Programming

Negative Indexing
In negative indexing, the indexing of elements starts from the end of the
tuple. That is the last element of the tuple is said to be at a position at -1 and
the previous element at -2 and goes on till the first element.
In the below figure, we can see how an element is associated with its index or
position of a tuple.

Exp of negative Indexing


tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(-2))
print(tuple(-8))

Output
The above code produces the following results
4
2

Create a tuple and a slice object. Use the slice object to get only the two first items of the
tuple:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(2)
print(a[x])
output
('a', 'b')

Create a tuple and a slice object. Start the slice object at position 3, and slice to position 5,
and return the result:

Prof. K.D.DONGARE
Python Programming

a = ("a", "b", "c", "d", "e", "f", "g", "h")


x = slice(3, 5)
print(a[x])

output
('d', 'e')

Create a tuple and a slice object. Use the step parameter to return every third item:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])

Output
('a', 'd', 'g')

Ex.
tuple= ('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])
print(tuple[-1:-5:-2])

Output
The above code produces the following results
('a', 'b', 'c', 'd', 'e', 'f')
('b', 'd', 'f', 'h')
('j', 'h')

Prof. K.D.DONGARE
Python Programming

In Python, slicing a list of tuples allows you to extract specific subsets of data efficiently.
Tuples, being immutable, offer a stable structure. Use slicing notation to select ranges or
steps within the list of tuples. This technique is particularly handy when dealing with
datasets or organizing information.

Slice A List Of Tuples in Python


To Slice A List Of Tuples In Python.
 Basic Slicing
 Using Negative Indices
 Using For Loop

Basic Slicing
In this example, the below code initializes a list of tuples and then extracts a sub list
containing tuples at index 1 and 2 (inclusive) using slicing.
The result is `sliced` containing `[(2, 'banana'), (3, 'orange')]`, which is then printed.
# Initialize list of tuples
tuples = [(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]

# Extract elements from index 1 to 2


sliced = tuples[1:3]
# Display list
print(sliced)

Output
[(2, 'banana'), (3, 'orange')]
Slice A List Of Tuples In Python Using Negative Indices
In this example, below code initializes a list of tuples and then extracts a sublist
containing tuples from the third last to the second last position using negative indexing.
The result is `sliced_list` containing `[(2, 'banana'), (3, 'orange')]`, which is then printed.
# Initialize list of tuples
tuples = [(1, 'apple'), (2, 'banana'), (3, 'orange'), (4, 'grape')]

# Extract elements from the third last to the second last

Prof. K.D.DONGARE
Python Programming

sliced = tuples[-3:-1]
# Display list oftuples
print(sliced)

Output
[(2, 'banana'), (3, 'orange')]

Ex.

my_tuple = ('t', 'u', 'r', 'i', 'a', 'l', 's', 'p','o', 'i', 'n', 't')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[5:12]) #Print elements from index 1 to index 3
print(my_tuple[::5]) #Print elements from start to end using step size
print(my_tuple[::-1]) #Print elements from end to start (reverse)

Output
('u', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'u')
('l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'l', 'n')
('t', 'n', 'i', 'o', 'p', 's', 'l', 'a', 'i', 'r', 'u', 't')

Prof. K.D.DONGARE
Python Programming

Basic Tuple Operations


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))

# Using Built-in Function


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

Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')

Prof. K.D.DONGARE
Python Programming

 Creating a Tuple with Mixed Datatypes.


Tuples can contain elements of various data types, including other
tuples, lists, dictionaries and even functions.
Example:
# Creating a Tuple with Mixed Datatype
tup = (5, 'Welcome', 7, 'Geeks')
print(tup)

# Creating a Tuple with nested tuples


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

# Creating a Tuple with repetition


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

# Creating a Tuple with the use of loop


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

Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')
('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
Prof. K.D.DONGARE
Python Programming

((((('Geeks',),),),),)

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.
Example:
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])

# Accessing a range of elements using slicing


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

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

# This line unpack values of Tuple1


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

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

Prof. K.D.DONGARE
Python Programming

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.

tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 = tup1 + tup2


print(tup3)

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

Prof. K.D.DONGARE
Python Programming

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.

# Slicing of a Tuple with Numbers


tup = tuple('GEEKSFORGEEKS')

# print from index 1 First element


print(tup[1:])

# Reversing the Tuple


print(tup[::-1])

# Printing elements of a Range


print(tup[4:9])

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

Prof. K.D.DONGARE
Python Programming

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)
output
display error

How to find Tuple Length


To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
tuple = ("apple", "banana", "cherry")
print(len(tuple))

Output
3
Concatenate tuples
we add two tuples and return the concatenated tuple

step-by-step approach :
1. Initialize two tuples with elements (1, 3, 5) and (4, 6) respectively and assign them
to the variables test_tup1 and test_tup2.
2. Print the original values of the two tuples using print() function and concatenate
them with the string using + operator.
3. Concatenate the two tuples test_tup1 and test_tup2 using + operator and assign
the result to a new variable res.
4. Print the concatenated tuple res using print() function and concatenate it with the
string using + operator.
5. End of the program.

Prof. K.D.DONGARE
Python Programming

# initialize tuples
tup1 = (1, 3, 5)
tup2 = (4, 6)

# printing original tuples


print("The original tuple 1 : ",tup1)
print("The original tuple 2 : ", tup2)

# Ways to concatenate tuples


# using + operator
res = tup1 + tup2

# printing result
print("The tuple after concatenation is : ", res)

output
The original tuple 1 : (1, 3, 5)
The original tuple 2 : (4, 6)
The tuple after concatenation is : (1, 3, 5, 4, 6)

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

count( ) Returns the frequency of occurrence of a specified value

Tuple Built-In Functions

Built-in Function Description

all() Returns true if all element are true or if tuple is empty

Prof. K.D.DONGARE
Python Programming

Built-in Function Description

return true if any element of the tuple is true. if tuple is empty, return
any() false

len() Returns length of the tuple or size of the tuple

enumerate() Returns enumerate object of tuple

max() return maximum element of given tuple

min() return minimum element of given tuple

sum() Sums up the numbers in the tuple

sorted() input elements in the tuple and return a new sorted list

tuple() Convert an iterable to a tuple.

Tuples VS Lists

Similarities Differences

Methods that cannot be used for


Functions that can be used for both lists and
tuples:
tuples:
append(), insert(), remove(), pop(),
len(), max(), min(), sum(), any(), all(), sorted()
clear(), sort(), reverse()

Methods that can be used for both lists and we generally use ‘tuples’ for
tuples: heterogeneous (different) data types
and ‘lists’ for homogeneous (similar)
count(), Index() data types.

Iterating through a ‘tuple’ is faster than


Tuples can be stored in lists.
in a ‘list’.

Lists can be stored in tuples. ‘Lists’ are mutable whereas ‘tuples’ are
Prof. K.D.DONGARE
Python Programming

Similarities Differences

immutable.

Tuples that contain immutable


Both ‘tuples’ and ‘lists’ can be nested. elements can be used as a key for a
dictionary.

Prof. K.D.DONGARE
Python Programming

Set

Sets in Python
A Set in Python is used to store a collection of items with the following properties.
 No duplicate elements. If try to insert the same item again, it overwrites previous
one.
 An unordered collection. When we access all items, they are accessed without any
specific order and we cannot access items using indexes as we do in lists.
 Internally use hashing that makes set efficient for search, insert and delete
operations. It gives a major advantage over a list for problems with these
operations.
 Mutable, meaning we can add or remove elements after their creation, the
individual elements within the set cannot be changed directly.

What is a set in Python?


A set in Python is an unordered collection of unique elements. It is defined by enclosing a
comma-separated sequence of elements within curly braces {}.

How do you create an empty set in Python?


You can create an empty set using the set() constructor: my_set = set().

How do you add elements to a set in Python?


You can add elements to a set using the add() method. For example: my_set.add(42).

Can a set contain duplicate elements?


No, a set in Python cannot contain duplicate elements. It automatically removes
duplicates

What is the difference between a set and a list in Python?


The main difference is that a set contains unique elements in an unordered fashion, while
Prof. K.D.DONGARE
Python Programming

a list can contain duplicate elements in a specific order.

How do you check if an element is in a set?


You can use the in keyword to check if an element is in a set. For example: if 42 in my_set

How to Creating Sets:


Creating a set in Python is straight forward. You can use curly braces {} or the set()
constructor to initialize an empty set. To create a set with initial elements, simply provide
them as a comma-separated list within curly braces. Let’s look at some examples:
# Creating an empty set
empty_set = set()

# Creating a set with elements


fruits = {"apple", "banana", "cherry"}

# Using the set() constructor


colors = set(["red", "green", "blue"])

Sets Operations :
Adding Elements

You can add elements to a set using the add() method:


fruits.add("orange")

Removing Elements
 To remove elements from a set, you can use the remove() method. It will raise a
KeyError if the element is not present in the set. Alternatively, you can use the
discard() method, which won’t raise an error if the element is not found:
fruits.remove("banana")
fruits.discard("watermelon")
Ex. Demonstrate union operation
A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}

Prof. K.D.DONGARE
Python Programming

print('A U B =', A| B)
print('B U C =', B | C)
print('A U B U C =', A | B | C)

Output
A U B = {2, 'a', 'd', 'c'}
B U C = {1, 2, 3, 'd', 'c'}
A U B U C = {1, 2, 3, 'd', 'c', 'a'}
Note that even after UNION operation , resulting set-c will not contain duplicate element

Set intersection
The intersection() method returns a new set with elements that are common to all sets.
Example
A = {2, 3, 5}
B = {1, 3, 5}

# compute intersection between A and B


print(A.intersection(B))

Output: {3, 5}

Example of Python Sets


s = {10, 50, 20}
print(s)
print(type(s))
Output
{10, 50, 20}
<class 'set'>
Note : There is no specific order for set elements to be printed

The Python set() method is used for type casting.


# typecasting list to set
s = set(["a", "b", "c"])
Prof. K.D.DONGARE
Python Programming

print(s)

# Adding element to the set


s.add("d")
print(s)

Output
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}

Python sets cannot have duplicate values. While you cannot modify the individual
elements directly, you can still add or remove elements from the set.
# a set cannot have duplicate values
# and we cannot change its items

# a set cannot have duplicate values


s = {"Geeks", "for", "Geeks"}
print(s)

# values of a set cannot be changed


s[1] = "Hello"
print(s)
Output:
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment

The first code explains that the set cannot have a duplicate value. Every item in it is a
unique value.
The second code generates an error because we cannot assign or change a value once the
set is created. We can only add or delete items in the set.

Set Operation
 Sets support various operations that are common in mathematics.

These include:
Prof. K.D.DONGARE
Python Programming

 Union: union() or |
 Intersection: intersection() or &
 Difference: difference() or –
 Symmetric Difference: symmetric_difference() or ^
 Subset: issubset()
 Superset: issuperset()
 Here’s an example demonstrating some of these operations:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Union
union_set = set1.union(set2)

# Intersection
intersection_set = set1.intersection(set2)

# Difference
difference_set = set1.difference(set2)

# Symmetric Difference
symmetric_difference_set = set1.symmetric_difference(set2)

# Subset
is_subset = set1.issubset(set2)

# Superset
is_superset = set1.issuperset(set2)

# A Python program to
# demonstrate adding elements
# in a set

# Creating a Set
student = {"Jay", "Idrish", "Archi"}

Prof. K.D.DONGARE
Python Programming

print("People:", student)

# This will add Daxit in the set

student.add("Daxit")
print("People:", student)

# Adding elements to the


# set using iterator
for i in range(1, 6):
student.add(i)

print("\nSet after adding element:", end = " ")


print(student)

Adding element in to set using Update() and add() function


Python Set update() Method Syntax
Syntax : set1.update(set2)
Here set1 is the set in which set2 will be added.

Insert the items from set y into set x:


x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.update(y)

print(x)

Output
{'microsoft', 'apple', 'banana', 'cherry', 'google'}

Ex.
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}

x.update(y)

print(x)

Prof. K.D.DONGARE
Python Programming

x.update ([4,5],{3,5,6})
print(x)

x.update (["ajay",5],{"vir",5,6})
print(x)

Clearing Python Sets


Set Clear() method empties the whole set in place.
# Python program to demonstrate clearing of set

set1 = {1,2,3,4,5,6}

print("Initial set")
print(set1)
# This method will remove all the elements of the set
set1.clear()

print("\nSet after using clear() function")


print(set1)

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

Set after using clear() function


set()

Union operation on Python Sets


Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements,
at the same time duplicates are removed.
# Python Program to demonstrate union of two sets

people = {"Jay", "Idrish", "Archil"}


year-2 = {"Karan", "Arjun"}

Prof. K.D.DONGARE
Python Programming

year-1 = {"Deepanshu", "Raju"}

# Union using union()


# function
population = people.union(year-2)

print("Union using union() function")


print(population)

# Union using "|"


# operator
population = people| year-1

print("\nUnion using '|' operator")


print(population)

Output
Union using union() function
{'Idrish', 'Arjun', 'Jay', 'Karan', 'Archil'}

Union using '|' operator


{'Idrish', 'Deepanshu', 'Raju', 'Jay', 'Archil'}

Prof. K.D.DONGARE
Python Programming

Union of Two Sets

The union of two sets A and B includes all the elements of sets A and B.

Set Union in Python

We use the | operator or the union() method to perform the set union operation. For example,

# first set

A = {1, 3, 5}

# second set

B = {0, 2, 4}

# perform union operation using |

print('Union using |:', A | B)

# perform union operation using union()

print('Union using union():', A.union(B))

Prof. K.D.DONGARE
Python Programming

Set Intersection

The intersection of two sets A and B include the common elements between set A and B.

Set Intersection in Python

In Python, we use the & operator or the intersection() method to perform the set intersection operation. For
example,

# first set

A = {1, 3, 5}

# second set

B = {1, 2, 3}

# perform intersection operation using &

print('Intersection using &:', A & B)

# perform intersection operation using intersection()

print('Intersection using intersection():', A.intersection(B))

Output

Intersection using &: {1, 3}

Prof. K.D.DONGARE
Python Programming
Intersection using intersection(): {1, 3}

Difference between Two Sets

The difference between two sets A and B include elements of set A that are not present on set B.

Set Difference in Python

We use the - operator or the difference() method to perform the difference between two sets. For example,

# first set

A = {2, 3, 5}

# second set

B = {1, 2, 6}

# perform difference operation using &

print('Difference using &:', A - B)

# perform difference operation using difference()

print('Difference using difference():', A.difference(B))

Output

Difference using &: {3, 5}

Difference using difference(): {3, 5}

Prof. K.D.DONGARE
Python Programming

Set Symmetric Difference

The symmetric difference between two sets A and B includes all elements of A and B without the common elements.

Set Symmetric Difference in Python

In Python, we use the ^ operator or the symmetric_difference() method to perform symmetric differences between
two sets. For example,

# first set

A = {2, 3, 5}

# second set

B = {1, 2, 6}

# perform difference operation using &

print('using ^:', A ^ B)

# using symmetric_difference()

print('using symmetric_difference():', A.symmetric_difference(B))

Output

using ^: {1, 3, 5, 6}

using symmetric_difference(): {1, 3, 5, 6}

Prof. K.D.DONGARE
Python Programming

Check if two sets are equal

We can use the == operator to check whether two sets are equal or not. For example,

# first set

A = {1, 3, 5}

# second set

B = {3, 5, 1}

# perform difference operation using &

if A == B:

print('Set A and Set B are equal')

else:

print('Set A and Set B are not equal')

Prof. K.D.DONGARE
Python Programming

Additional Set Function

Prof. K.D.DONGARE
Python Programming
Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

Returns the difference of two or more sets as a


difference()
new set

difference_update() Removes all elements of another set from this set

Removes an element from the set if it is a


discard()
member. (Do nothing if the element is not in set)

intersection() Returns the intersection of two sets as a new set

Updates the set with the intersection of itself and


intersection_update()
another

isdisjoint() Returns True if two sets have a null intersection

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitrary set element.


pop()
Raises KeyError if the set is empty

Removes an element from the set. If the element


remove()
is not a member, raises a KeyError

Returns the symmetric difference of two sets as a


symmetric_difference()
new set

Updates a set with the symmetric difference of


symmetric_difference_update()
itself and another

union() Returns the union of sets in a new set

Updates the set with the union of itselfProf.


andK.D.DONGARE
update()
others
Python Programming

Python Dictionary
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists and tuples,
each item in a dictionary is a key-value pair (consisting of a key and a value).

Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by commas. For example,
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# printing the dictionary


print(country_capitals)

Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'England': 'London'}

The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the key and 'Berlin' is the
value assigned to it and so on.

Access Dictionary Items


We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}

# access the value of keys


print(country_capitals["Germany"]) # Output: Berlin
print(country_capitals["England"]) # Output: London

Prof. K.D.DONGARE
Python Programming

Add Items to a Dictionary


We can add an item to a dictionary by assigning a value to a new key. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# add an item with "Italy" as key and "Rome" as its value


country_capitals["Italy"] = "Rome"

print(country_capitals)

Output
{'Germany': 'Berlin', 'Canada': 'Ottawa', 'Italy': 'Rome'}

Remove Dictionary Items


We can use the del statement to remove an element from a dictionary. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# delete item having "Germany" key


del country_capitals["Germany"]

print(country_capitals)

Output
{'Canada': 'Ottawa'}

If we need to remove all items from a dictionary at once, we can use the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}

# clear the dictionary


country_capitals.clear()

print(country_capitals)

Output
{}

Prof. K.D.DONGARE
Python Programming

Change Dictionary Items


Python dictionaries are mutable (changeable). We can change the value of a dictionary element by referring to its
key. For example,
country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London"
}

# change the value of "Italy" key to "Rome"


country_capitals["Italy"] = "Rome"

print(country_capitals)

Output
{'Germany': 'Berlin', 'Italy': 'Rome', 'England': 'London'}

Iterate Through a Dictionary


A dictionary is an ordered collection of items (starting from Python 3.7), therefore it maintains the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome" }

# print dictionary keys one by one

for country in country_capitals:


print(country)

print()

# print dictionary values one by one


for country in country_capitals:
capital = country_capitals[country]
print(capital)

Output
United States
Italy
Washington D.C.
Rome

Prof. K.D.DONGARE
Python Programming

Find Dictionary Length


We can find the length of a dictionary by using the len() function.
country_capitals = {"England": "London", "Italy": "Rome"}

# get dictionary's length


print(len(country_capitals)) # Output: 2

numbers = {10: "ten", 20: "twenty", 30: "thirty"}

# get dictionary's length


print(len(numbers)) # Output: 3

countries = {}

# get dictionary's length


print(len(countries)) # Output: 0

Dictionary Membership Test


We can check whether a key exists in a dictionary by using the in and not in operators.
file_types = {
".txt": "Text File",
".pdf": "PDF Document",
".jpg": "JPEG Image",
}

# use of in and not in operators


print(".pdf" in file_types) # Output: True
print(".mp3" in file_types) # Output: False
print(".mp3" not in file_types) # Output: True
Note: The in operator checks whether a key exists; it doesn't check whether a value exists or not.

Prof. K.D.DONGARE
Python Programming

Python Dictionary Methods


Here are some of the commonly used dictionary methods.

Function Description

pop() Removes the item with the specified key.

update() Adds or changes dictionary items.

clear() Remove all the items from the dictionary.

keys() Returns all the dictionary's keys.

values() Returns all the dictionary's values.

get() Returns the value of the specified key.

popitem() Returns the last inserted key and value as a tuple.

copy() Returns a copy of the dictionary.

Prof. K.D.DONGARE

You might also like