0% found this document useful (0 votes)
7 views

Chapter 3

This document provides a comprehensive overview of lists in Python, detailing their characteristics, creation, indexing, and various operations such as slicing, iterating, and built-in functions. It explains how to declare lists, access elements using positive and negative indexing, and perform operations like appending, inserting, and removing elements. Additionally, it introduces tuples, highlighting their immutability compared to lists.

Uploaded by

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

Chapter 3

This document provides a comprehensive overview of lists in Python, detailing their characteristics, creation, indexing, and various operations such as slicing, iterating, and built-in functions. It explains how to declare lists, access elements using positive and negative indexing, and perform operations like appending, inserting, and removing elements. Additionally, it introduces tuples, highlighting their immutability compared to lists.

Uploaded by

gangaikwad102
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

3.

1 LIST
A list is a data type that allows you to store various types of data in it.
List is a compound data type which means you can have different-2 data types under a list, for
example we can have integer, float and string items in a same list.
The list will be ordered and there will be a definite count of it.
The elements are indexed according to a sequence and the indexing is done with 0 as the first
index.
Each element will have a distinct place in the sequence and if the same value occurs multiple times
in the sequence, each will be considered separate and distinct element.

A] Declaring / Creating / Defining List


In Python programming, a list is created by placing all the items (elements) inside a square bracket
[ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

B] Accessing the items of a list


We can use the index operator [ ] to access an item in a list. Index starts from 0.
So, a list having 5 elements will have index from 0 to 4.
Syntax to access the list items:
list_name[index]

Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
# prints 300
print(numbers[5])
# prints 22
print(numbers[1])
Output:
11
300
22

Points to Note:
The index cannot be a float number.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]

# error
print(numbers[1.0])

Output:
TypeError: list indices must be integers or slices, not float

1. The index must be in range to avoid IndexError. The range of the index of a list having 10
elements is 0 to 9, if we go beyond 9 then we will get IndexError. However if we go below 0
then it would not cause issue in certain cases, we will discuss that in our next section.

For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]

# error
print(numbers[6])

Output:
IndexError: list index out of range

C] Negative Index to access the list items from the end


Unlike other programming languages where negative index may cause issue, Python allows you to
use negative indexes. The idea behind this to allow you to access the list elements starting from the
end. For example an index of -1 would access the last element of the list, -2 second last, -3 third
last and so on.
Example of Negative indexes in Python

# a list of strings
my_list = ["hello", "world", "hi", "bye"]

# prints "bye"
print(my_list[-1])
# prints "world"
print(my_list[-3])

# prints "hello"
print(my_list[-4])

Output:
bye
world
hello

Example 2:
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])

D] Slicing list/ Range of Indexes


We can get a sublist from a list in Python using slicing operation.
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Lets say we have a list n_list having 10 elements, then we can slice this list using colon : operator.

list = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(list[2:5])
The search will start at index 2 (included) and end at index 5 (not included)

Example
n_list = ['P','Y','T','H','O','N','P','R','O','G']

#The search will start at index 1 (included) and end at index 3 (not included)
print(n_list[1:3])
print(n_list[:3])
print(n_list[3:])
print(n_list[:-5])
print(n_list[-3:])
print(n_list[-7:-3])

# Whole list
print(n_list[:])

# Whole list in reverse order


print(n_list[::-1])

Output:

['Y', 'T']
['P', 'Y', 'T']
['H', 'O', 'N', 'P', 'R', 'O', 'G']
['P', 'Y', 'T', 'H', 'O']
['R', 'O', 'G']
['H', 'O', 'N', 'P']
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G']
['G', 'O', 'R', 'P', 'N', 'O', 'H', 'T', 'Y', 'P']

E] Iterating through List using for loop


list1=[45,15,444,"ravi",941,"akshay",200]
for i in list1 :
print(i)
output
42
15
444
ravi
941
akshay
200

The same program can be written by directly placing list in for-loop


for i in [45,15,444,"ravi",941,"akshay",200]:
print(i)

Above code will also give the same output.

Program to perform sum of elements


list1=[1,2,3,4,5,6,7,8,9,10]
sum=0
for i in list1:
sum=sum+i
print("sum of elements is",sum)
Output:
sum of elements is 55

F] Basic List operations/ Built in List Functions


Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

1. Adding and Appending

 append(): Used for appending and adding elements to List. It is used to add elements to the
last position of List.

 Syntax:
list.append(element)

# Adds List Element as value of List.


List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)

Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]
 insert(): Inserts an elements at specified position.

Syntax:
list.insert(position, element)

Note: Position mentioned should be within the range of List, as in this case between 0 and 4,
elsewise would throw IndexError.

List = ['Mathematics', 'chemistry', 1997, 2000]


# Insert at index 2 value 10087
List.insert(2,10087)
print(List)

Output:
['Mathematics', 'chemistry', 10087, 1997, 2000]

 extend(): Adds contents of List2 to the end of List1.

Syntax:

List1.extend(List2)

List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]

# Add List2 to List1


List1.extend(List2)
print(List1)

# Add List1 to List2 now


List2.extend(List1)
print(List2)

Output:

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

2. sum(), count(), index(), min() and max() functions of List

 sum() : Calculates sum of all the elements of List.

 Syntax:

sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))

Output:
15

What happens if numeric value is not used a parameter?

Sum is calculated only for Numeric values, elsewise throws TypeError.


See example:

List = ['gfg', 'abc', 3]


print(sum(List))

Output:
Traceback (most recent call last):
File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

 count():Calculates total occurrence of given element of List.

 Syntax:
List.count(element)

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))

Output:
4

 len: Calculates total length of List.

 Syntax:

len(list_name)

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))

Output:
10
 index(): Returns the index of first occurrence. Start and End index are not necessary
parameters.

 Syntax:

List.index(element[,start[,end]])

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))

Output:
1

Another example:

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2,2))

Output:
4

List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]

"""index(element, start, end) : It will calculate till index end-1. """

# will check from index 2 to 4.


print("After checking in index range 2 to 4")
print(List.index(2,2,5))

# will check from index 2 to 3.


print("After checking in index range 2 to 3")
print(List.index(2,2,4))

Output:

After checking in index range 2 to 4

4
After checking in index range 2 to 3
Traceback (most recent call last):
File "C:/Python/Python38/list_index.py", line 10, in <module>
print(List.index(2,2,4))
ValueError: 2 is not in list
 min() : Calculates minimum of all the elements of List.

 Syntax:

min(List)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(min(List))

Output:
1.054

 max(): Calculates maximum of all the elements of List.

 Syntax:

max(List)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(max(List))

Output:
5.33

3. sort() and reverse() functions

The sort() method sorts the items of a list in ascending or descending order.
Syntax:
list.sort([key,[Reverse]])

By default, sort() doesn't require any extra parameters.


However, it has two optional parameters:
reverse - If True, the sorted list is reversed (or sorted in Descending order)
key - function that serves as a key for the sort comparison

The sort() method doesn't return any value. Rather, it changes the original list.
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)

Output
Sorted list: ['a', 'e', 'i', 'o', 'u']
sort in Descending order
The sort() method accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the list in the descending order.
list.sort(reverse=True)

Example:

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


vowels.sort(reverse=True)

# print vowels
print('Sorted list in Descending:', vowels)

Output

Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']

sorted()
If you want a function to return the sorted list rather than change the original list, use
sorted().
The simplest difference between sort() and sorted() is: sort() changes the list directly and
doesn't return any value, while sorted() doesn't change the list and returns the sorted list.

 Syntax:
sorted([list[,key[,Reverse]]])
Key and reverse are not necessary parameter and reverse is set to False, if nothing is passed
through sorted().
Examples:
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']

# sort the vowels


print("Sorted List is ",sorted(vowels,reverse=True))
4. Deletion of List Elements

To Delete one or more elements, i.e. remove an element, many built in functions can be used, such
as pop() & remove() and keywords such as del.

 pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs.

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop())

Output:
2.5

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


print(List.pop(0))
print (Lis)

Output:
2.3

 del() : Element to be deleted is mentioned using list name and index.


Syntax:
del list[index]

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


del List[0]
print(List)

Output:
[4.445, 3, 5.33, 1.054, 2.5]

 remove(): Element to be deleted is mentioned using list name and element.


Syntax:
list.remove(element)

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]


List.remove(3)
print(List)

Output:
[2.3, 4.445, 5.33, 1.054, 2.5]
All Functions on List:-
List1 = [1,2,3,4,2,2,5,2]
List2 = [10,20,30]
List1.append(6)
print(List1)

List1.insert(2,10)
print(List1)

List2.extend(List1)
print(List2)

print(sum(List1))
print(List1.count(2))

print(len(List1))

print(List1.index(2))

print(min(List1))

print(max(List1))

List1.sort(reverse=True)
print(List1)

print(sorted(List1,reverse=True))

print(List1.pop(4))
print(List1)

del List1[2]
print(List1)

List1.remove(5)
print(List1)
3.2 Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas, in a list, elements can be changed.

A] 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.).

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(my_tuple)

Otput
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Note:

1. type() is a function that returns type (datatype) of parameter value/object.


2. An empty tuple with parenthesis is valid, but is of no use, because we can change its
elements, if required.
3. Having one element within parentheses is not enough. We will need a trailing comma to
indicate that it is, in fact, a tuple.

Example:

# Creating a tuple having no element


my_tuple =()
print(type(my_tuple)) # <class 'tuple'>

# Creating a tuple having one element


my_tuple =(10)
print(type(my_tuple)) #<class 'int'>

my_tuple = (10,20)
print(type(my_tuple)) # <class 'tuple'>

my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>

# Creating a tuple having one element


my_tuple = ("hello",)
print(type(my_tuple)) # <class 'tuple'>

# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>

Output:

<class 'tuple'>
<class 'int'>
<class 'tuple'>
<class 'str'>
<class 'tuple'>
<class 'tuple'>
B] Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an element outside of
tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
my_tuple = ('p','e','r','m','i','t')

print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'

# IndexError: list index out of range


# print(my_tuple[6])

# Index must be an integer


# TypeError: list indices must be integers, not float
# my_tuple[2.0]

# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4

Output

p
t
s
4

C] Negative Indexing
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.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])

Output
t
p
D] Slicing operation in tuples
We can access a range of items in a tuple by using the slicing operator - colon ":".

my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)

# prints (33, 44, 55)


print(my_data[2:5])

# prints (11, 22, 33, 44)


print(my_data[:4])

# prints (55, 66, 77, 88, 99)


print(my_data[4:])

# prints (55, 66, 77, 88)


print(my_data[4:-1])

# displaying entire tuple


print(my_data[:])

Output:

(11, 22, 33, 44, 55, 66, 77, 88, 99)


(33, 44, 55)
(11, 22, 33, 44)
(55, 66, 77, 88, 99)
(55, 66, 77, 88)
(11, 22, 33, 44, 55, 66, 77, 88, 99)

Slicing can be best visualized by considering the index to be between the elements as shown below.
So if we want to access a range, we need the index that will slice the portion from the tuple.
E] Iteration through Tuple using for-loop

Iterating a tuple
# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")

# iterating over tuple elements


for fruit in my_tuple:
print(fruit)
Output:
Apple
Orange
Grapes
Banana

F] Membership Test in Tuples


in: Checks whether an element exists in the specified tuple.
not in: Checks whether an element does not exist in the specified tuple.
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)

# true
print(22 in my_data)

# false
print(2 in my_data)

# false
print(88 not in my_data)

# true
print(101 not in my_data)
Output:
(11, 22, 33, 44, 55, 66, 77, 88, 99)
True
False
False
True

G] Basic Tuple Operations

1. Unlike lists, tuples are immutable.


This means that elements of a tuple cannot be changed once it has been assigned.
But, if the element is itself a mutable datatype like list, its nested items can be
changed.
We can also assign a tuple to different values (reassignment).

my_tuple = (4, 2, 3, [6, 5])

# TypeError: 'tuple' object does not support item assignment


# my_tuple[1] = 9

# However, item of mutable element can be changed

my_tuple[3][0] = 9 # Output: (4, 2, 3, [9, 5])


print(my_tuple)

# Tuples can be reassigned


my_tuple = ('p','r','o','g','r','a','m','i','z')

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)

Output
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

2. Concatenation / Repetition / Nesting of Tuples


We can use + operator to combine two tuples. This is also called concatenation.
We can also repeat the elements in a tuple for a given number of times using the * operator.
Both + and * operations result in a new tuple.

# Code for concatenating 2 tuples


tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'Arrow')
# Concatenating above two
print(tuple1 + tuple2)

Output:
(0, 1, 2, 3, 'python', 'Arrow')

Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'geek'))

Repetition in Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)

Output
('python', 'python', 'python')

3. Deleting a Tuple
We cannot change the elements in a tuple. That also means we cannot delete or remove items from
a tuple.
But deleting a tuple entirely is possible using the keyword del.

# Code for deleting a tuple


tuple3 = ( 0, 1)
del tuple3
print(tuple3)

Error:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined

4. Finding Length of a Tuple

# Code for printing the length of a tuple


tuple2 = ('python', Arrow)
print(len(tuple2))

Output
2

H] Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
Python Tuple Method

Method Description

count(x) Returns the number of items x

index(x) Returns the index of the first item that is equal to x

Some examples of Python tuple methods:


my_tuple = ('a','p','p','l','e',)
print(my_tuple.count('p'))
print(my_tuple.index('l'))

Output:

2
3

Advantages of Tuple over List


Since tuples are quite similar to lists, both of them are used in similar situations as well.
However, there are certain advantages of implementing a tuple over a list.
 We generally use tuple for heterogeneous (different) datatypes and list for homogeneous
(similar) datatypes.
 Since tuples are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
 Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is
not possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains
write-protected.
3.3 SET
A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).
However, the set itself is mutable. We can add or remove items from it.
Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

A] Declaring Set or Defining Set or Creating Set

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
But a set cannot have a mutable element, like list, set or dictionary, as its element.

Example

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Output
{1, 2, 3}
{1.0, 'Hello', (1, 2, 3)}

In above example, Set contains immutable elements like tuple, float and string. We can not add list
element in set. See below example

my_set = {1, 2, [3, 4]}

# set cannot have mutable items, here [3, 4] is a mutable list


# If you run above code, this will cause an error. TypeError: unhashable type: 'list'
Example 2:

# set do not have duplicates


my_set = {1,2,3,4,3,2}
print(my_set)

# we can make set from a list


my_set = set([1,2,3,2])
print(my_set)

Output:
{1, 2, 3, 4}
{1, 2, 3}

Creating an empty set is a bit tricky.


Empty curly braces {} will make an empty dictionary in Python.
To make a set without any elements we use the set() function without any argument.

# initialize a with {}
a = {}

# check data type of a


print(type(a))

# initialize a with set()


a = set()

# check data type of a


print(type(a))

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

B] Set object does not support indexing.


Sets are mutable. But since they are unordered, indexing have no meaning.
We cannot access or change an element of set using indexing or slicing. Set does not support it.

Example1
my_set = {1,3}
my_set[0]

# if you run above code you will get an error TypeError: 'set' object does not support indexing
C] Adding element to set

We can add single element using the add() method and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as
its argument. In all cases, duplicates are avoided.

Example:

# initialize my_set
my_set = {1,3}
print(my_set)

# add an element
my_set.add(2)
print(my_set)

# add multiple elements


my_set.update([2,3,4])
print(my_set)

# add list and set


my_set.update([4,5], {1,6,8})
print(my_set)

Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
D] Remove element from set:

discard / remove

A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not exist in the
set, it remains unchanged.
But remove() will raise an error in such condition.
The following example will illustrate this.

Example 1:

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

my_set.discard(4) # discard an element


print(my_set)

my_set.remove(6) # remove an element

print(my_set)

Output:

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

Example 2:

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element not present in my_set


my_set.discard(2)
print(my_set)

Output:
{1, 3, 4, 5, 6}
{1, 3, 4, 5, 6}
Here the element 2 is not in the set, but discard will do nothing and set will remain unchanged.
Example 3:

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
my_set.remove(2)
print(my_set)

Here element 2 is not present in set


If you run above code you will get an error Output as
Traceback (most recent call last):
File "C:/Python/Python38/delete_set_ele.py", line 4, in <module> my_set.remove(2) KeyError: 2

pop / clear

Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped.
It is completely arbitrary.
We can also remove all items from a set using clear().

my_set = set("HelloWorld") # initialize my_set


print(my_set)

print(my_set.pop()) # pop an element Output will be random element


print(my_set)

print(my_set.pop()) # pop another element Output: random element


print(my_set)

my_set.clear() # clear my_set


print(my_set)

Output:

{'l', 'o', 'W', 'e', 'r', 'd', 'H'}


l
{'o', 'W', 'e', 'r', 'd', 'H'}
o
{'W', 'e', 'r', 'd', 'H'}
set()

Here the output may get changed every time as the sets are unordered and random element will be
popped every time.
E] Set Operations

Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

1. Set Union

Union of A and B is a set of all elements from both sets.


Union is performed using | operator. Same can be accomplished using the method union()

Example 1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B) # use | operator

Output:
{1, 2, 3, 4, 5, 6, 7, 8}

Example 2
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A)
print(B)
C=A.union(B) # use union function on B
print(C)
C= B.union(A) # use union function on B
print(C)

Output:

{1, 2, 3, 4, 5}
{4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}

2. Set Intersection

Intersection of A and B is a set of elements that are common in both sets.


Intersection is performed using & operator. Same can be accomplished using the
method intersection().

Exampe1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)

Output:
{4, 5}

Example2:

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.intersection(B))
# use intersection function on B
print(B.intersection(A))
Output:

{4, 5}
{4, 5}

3. Set Difference

Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a
set of element in B but not in A.
Difference is performed using - operator. Same can be accomplished using the method difference().

Example 1:

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use - operator on A
print(A - B)

Output:
{1, 2, 3}

Example: 2
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.difference(B))
print(B.difference(A))

Output:
{1, 2, 3}
{8, 6, 7}
4. Set Symmetric Difference

Symmetric Difference of A and B is a set of elements in both A and B except those that are common
in both.
Symmetric difference is performed using ^ operator.
Same can be accomplished using the method symmetric_difference().

Example 1:

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

# use ^ operator
print(A ^ B)

Output:
{1, 2, 3, 6, 7, 8}

Example 2:

# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}

print(A.symmetric_difference(B))
print(B.symmetric_difference(A)))

Output:
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
F] Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the keyword in .

# initialize my_set
my_set = set("apple")

# check if 'a' is present


print('a' in my_set)

# check if 'p' is present


print('p' not in my_set)

Output:

True
False

Iterating Through a Set


Using a for loop, we can iterate though each item in a set.

for letter in set("apple"):


print(letter)

Output:
a
p
e
l
G] Different Python Set Methods
There are many set methods, some of which we have already used above. Here is a list
of all the methods that are available with set objects.

Python Set Methods

Method Description

add() Adds an element to the set

clear() Removes all elements from the set

copy() Returns a copy of the set

difference() Returns the difference of two or more sets as a new set

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

discard() Removes an element from the set if it is a member. (Do nothing if


the element is not in set)

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

intersection_update() Updates the set with the intersection of itself and another

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

issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Removes and returns an arbitary set element. Raise KeyError if


pop()
the set is empty
Removes an element from the set. If the element is not a member,
remove()
raise a KeyError

symmetric_difference() Returns the symmetric difference of two sets as a new set

symmetric_difference_
Updates a set with the symmetric difference of itself and another
update()

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

update() Updates the set with the union of itself and others

# Python program to demonstrate working of Set in Python

# Creating two sets


set1 = set()
set2 = set()

# Adding elements to set1


for i in range(1, 6):
set1.add(i)

# Adding elements to set2


for i in range(3, 8):
set2.add(i)

print("Set1 = ", set1)


print("Set2 = ", set2)
print("\n")

# Union of set1 and set2


set3 = set1 | set2# set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)

# Intersection of set1 and set2


set4 = set1 & set2# set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")

# Checking relation between set3 and set4


if set3 > set4: # set3.issuperset(set4)
print("Set3 is superset of Set4")
elif set3 < set4: # set3.issubset(set4)
print("Set3 is subset of Set4")
else : # set3 == set4
print("Set3 is same as Set4")

# displaying relation between set4 and set3


if set4 < set3: # set4.issubset(set3)
print("Set4 is subset of Set3")
print("\n")

# difference between set3 and set4


set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")

# checkv if set4 and set5 are disjoint sets


if set4.isdisjoint(set5):
print("Set4 and Set5 have nothing in common\n")

# Removing all the values of set5


set5.clear()

print("After applying clear on sets Set5: ")


print("Set5 = ", set5)

Output:

Set1 = {1, 2, 3, 4, 5}
Set2 = {3, 4, 5, 6, 7}

Union of Set1 & Set2: Set3 = {1, 2, 3, 4, 5, 6, 7}


Intersection of Set1 & Set2: Set4 = {3, 4, 5}

Set3 is superset of Set4


Set4 is subset of Set3

Elements in Set3 and not in Set4: Set5 = {1, 2, 6, 7}

Set4 and Set5 have nothing in common

After applying clear on sets Set5:


Set5 = set()

H] Deleting Set

Similar to lists and tuple, we can also delete an entire set by using keyword “del” followed by set to
be deleted.
Example:

set1={10,20,30}
print(“Initially set1 contains : “ set1)
del set1
print(“After deletion, set1 contains”, set1)

This code will give error.


Output:
Initially set1 contains : {10, 20, 30}
Traceback (most recent call last):
File "C:/Python/Python38/set_del.py", line 4, in <module>
print("After deletion, set1 contains", set1)
NameError: name 'set1' is not defined
3.4 Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized.

A] Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’.
Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:value.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable.

Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.

# Creating a Dictionary with Integer Keys


Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

Output:

Dictionary with the use of Integer Keys:


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

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by
just placing to curly braces{}.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:

Empty Dictionary:
{}

Dictionary with the use of dict():


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

Dictionary with each item as a pair:


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

B] Accessing elements from a Dictionary


In order to access the items of a dictionary refer to its key name.
Key can be used inside square brackets.

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using key


print("Accessing a element using key:")
print(Dict[1])

Output:

Accessing a element using key:


For

Accessing a element using key:


Geeks

There is also a method called get() that will also help in acessing the element from a dictionary.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:

Accessing a element using get:


Geeks

C] Iterating Through a Dictionary


Using a for loop we can iterate though each key in a dictionary.

Example 1:

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}


for i in squares:
print(i)

Output:
1
3
9
5
7

Here i refers to key (index) of dictionary by default. If we want to print values of associated keys,
we use [] operator as follows.

Example 2:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output:
1
9
81
25
49
Python Dictionary Methods
Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples

1. Change or update Elements in Dictionary

Python Dictionary Methods

Method Description

clear() Remove all items form the dictionary.

copy() Return a shallow copy of the dictionary.

Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v (defaults to None).

Return the value of key. If key doesnot exit, return d


get(key[,d])
(defaults to None).

items() Return a new view of the dictionary's items (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value or d if key is
pop(key[,d]) not found. If d is not provided and key is not found, raises
KeyError.

Remove and return an arbitary item (key, value). Raises


popitem()
KeyError if the dictionary is empty.

If key is in the dictionary, return its value. If not, insert key


setdefault(key[,d])
with a value of d and return d (defaults to None).

Update the dictionary with the key/value pairs from other,


update([other])
overwriting existing keys.

values() Return a new view of the dictionary's values


a) update () function
Dictionary allows to change or add any key:value pair by using update() function. If the key is
already present, value gets updated else a new key:value pair is added to dictionary.
Example:

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print ("Initially Dictionary contains",Dict)


Dict.update({5:'akshay'})
print("After updation Dictionary contains",Dict)

Output:

Initially Dictionary contains {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


After updation Dictionary contains {1: 'Geeks', 'name': 'For', 3: 'Geeks', 5: 'akshay'}

We can append one dictionary with another dictionary using update ( ) function.

# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Dict2 = {'Nakul':'study','Navnath':'kharda'}
print ("Initially Dictionary contains",Dict1)
Dict1.update(Dict2)
print("After updation Dictionary contains",Dict1)

Output:

Initially Dictionary contains {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


After updation Dictionary contains {1: 'Geeks', 'name': 'For', 3: 'Geeks', 'Nakul': 'study', 'Navnath':
'kharda'}

b) Assignment operator:
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.

my_dict = {'name':'Jack', 'age': 26}


# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)

When you run the program, the output will be:

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

2. delete or remove elements

a) pop( )

We can remove a particular item in a dictionary by using the method pop(). This method removes
an item with the provided key and returns the value.

b) popitem()
The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary.

c) clear()
All the items can be removed at once using the clear() method.

d) del ()
We can also use the del keyword to remove individual items or the entire dictionary
itself.

# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item


print(squares.pop(4))

print(squares)

# remove an arbitrary item


print(squares.popitem())

print(squares)

# delete a particular item


del squares[5]

print(squares)

# remove all items


squares.clear()

print(squares)

# delete the dictionary itself


del squares

When you run the program, the output will be:

16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

3. keys() and values ()


keys() : Return a new view of the dictionary's keys.
values() : Return a new view of the dictionary's values

Example1:
# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print ("All the keys in dictionary are", Dict1.keys())
print ("All the values in dictionary are",Dict1.values())

Output:

All the keys in dictionary are dict_keys([1, 'name', 3])


All the values in dictionary are dict_values(['Geeks', 'For', 'Geeks'])

4. Finding lenth using _ _len_ _() function:


Example:

# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(Dict1.__len__())
Output:
3

You might also like