0% found this document useful (0 votes)
2 views24 pages

Python Unit 4

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views24 pages

Python Unit 4

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RENAISSANCE UNIVERSITY, INDORE

School of Computer Science


BCA/BSC III Sem

Subject: Fundamentals of Python


Unit 4

Lists in Python
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++
and ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and
separated by commas.

The list is a sequence data type which is used to store the collection of data.

Example:
Here we are creating Python List using [].

fruits = ["Apple", "Grapes", "Mango"]


print(fruits)

#Output: ['Apple', 'Grapes', 'Mango']

Lists are the simplest containers that are an integral part of the Python language. Lists need
not be homogeneous always which makes it the most powerful tool in Python.
A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable,
and hence, they can be altered even after their creation.

Creating List in Python:


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

Example 1: Creating a list in Python:


# Python program to demonstrate Creation of List

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

# Creating a List of numbers


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

# Creating a List of strings and accessing


# using index
List = ["Welcome", "To", "RU"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output:
Empty List:
[]

List of numbers:
[10, 20, 30]

List Items:
Welcome
RU

Example 2: Creating a list with multiple distinct or duplicate elements:


A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.
# Creating a List with the use of Numbers (Having duplicate values)
List = [1, 2, 4, 4, 4, 3, 3, 4, 5]
print("\nList with only numbers: ")
print(List)

# Creating a List with


# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'RU', 4, 'BCA', 6, 'BSC']
print("\nList with Mixed Values: ")
print(List)

Output:
List with only numbers:
[1, 2, 4, 4, 4, 3, 3, 4, 5]

List with Mixed Values:


[1, 2, 'RU', 4, 'BCA', 6, 'BSC']

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 1: Accessing elements from list:
# Python program to demonstrate accessing of element from list

# Creating a List with


# the use of multiple values
List = ["RU", "BCA", "BSC", 10.5, True]

# accessing a element from the


# list using index number
print("Accessing a element from the list")
print(List[0])
print(List[2])
print(List[3])
print(List[4])

Output:
Accessing a element from the list
RU
BSC
10.5
True

Negative indexing:
In Python, negative sequence indexes represent positions from the end of the array. Instead
of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
# Python program to demonstrate accessing of element from list

# Creating a List with


# the use of multiple values
List = ["RU", "BCA", "BSC", 10.5, True]

# accessing a element from the


# list using index number
print("Accessing a element from the list using negative indexing")
print(List[0])
print(List[-2])
print(List[-3])
print(List[-1])

Output:
Accessing a element from the list
RU
10.5
BSC
True

Getting the size of Python list:


Python len() is used to get the length of the list.

# Creating a List
List1 = []
print(len(List1)) # 0

# Creating a List of numbers


List2 = [10, 20, 14]
print(len(List2)) # 3

Taking Input of a Python List:


We can take the input of a list of elements as string, integer, float, etc. But the default one is
a string.

# Python program to take space separated input as a string


# split and store it to a list and print the string list

string = input("Enter elements (Space-Separated): ")

# split the strings and store it to a list


lst = [Link]()
print('The list of numbers is:', lst) # printing the list
Output:
Enter elements (Space-Separated): 1 2 3 4 5
The list of numbers is: ['1', '2', '3', '4', '5']

List Operations:
Adding Elements to a Python List
Method 1: 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. Tuples can also be added to the list with
the use of the append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.
# Python program to demonstrate Addition of elements in a List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Addition of Elements
# in the List
[Link](1)
[Link](2)
[Link](4)
print("\nList after Addition of Three elements: ")
print(List)

# Adding elements to the List


# using Iterator
for i in range(1, 4):
[Link](i)
print("\nList after Addition of elements from 1-3: ")
print(List)

Output:
Initial blank List:
[]

List after Addition of Three elements:


[1, 2, 4]

List after Addition of elements from 1-3:


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

Method 2: 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. Unlike append() which
takes only one argument, the insert() method requires two arguments(position, value).

# 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)
[Link](3, 12)
[Link](0, 'Hello')
print("\nList after performing Insert Operation: ")
print(List)

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

List after performing Insert Operation:


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

Method 3: Using extend() method:


Other than append() and insert() methods, there’s one more method for the Addition of
elements, extend(), this method is used to add multiple elements at the same time at the end
of the list.
Note: append() and extend() methods can only add elements at the end.
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 multiple elements


# to the List at the end
# (using Extend Method)
[Link]([8, 'Python', 'Java'])
print("\nList after performing Extend Operation: ")
print(List)

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

List after performing Extend Operation:


[1, 2, 3, 4, 8, 'Python', 'Java']

Reversing a List:
A list can be reversed by using the reverse() method in Python.
# Reversing a list
mylist = [1, 2, 3, 4, 5, 'Python', 'Java']
[Link]()
print("Reversed list is ", mylist) # Reversed list is ['Java', 'Python', 5,
4, 3, 2, 1]
Removing Elements from the List:
Method 1: Using remove() method
Elements can be removed from the List by using the built-in remove() function but an Error
arises if the element doesn’t exist in the list. Remove() method only removes one element at
a time, to remove a range of elements, the iterator is used. The remove() method removes
the specified item.

Note: Remove method in List will only remove the first occurrence of the searched element.

# Python program to demonstrate Removal of elements in a List

# Creating a List
List = [1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List)

# Removing elements from List


# using Remove() method
[Link](5)
[Link](6)
print("\nList after Removal of two elements: ")
print(List)

Output:
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements:


[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

Method 2: Using pop() method:


pop() function can also be used to remove and return an element from the list, but by default
it removes only the last element of the list, to remove an element from a specific position of
the List, the index of the element is passed as an argument to the pop() method.

Slicing of a List:
We can get substrings and sublists 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]

To print elements from end-use:


[:-Index]

To print elements from a specific Index till the end use


[Index:]
To print the whole list in reverse order, use
[::-1]

Note – To print elements of List from rear-end, use Negative Indexes.


Example:
# Python program to demonstrate Removal of elements in a List

# Creating a List
List = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'R', 'A', 'M', 'M', 'I',
'N', 'G']
print("Initial List: ")
print(List)

# Print elements of a range


# using Slice operation
Sliced_List = List[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_List)

# Print elements from a


# pre-defined point to end
Sliced_List = List[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_List)

# Printing elements from


# beginning till end
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

Output:
Initial List:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'R', 'A', 'M', 'M', 'I', 'N',
'G']

Slicing elements in a range 3-8:


['H', 'O', 'N', 'P', 'R']

Elements sliced from 5th element till the end:


['N', 'P', 'R', 'O', 'R', 'A', 'M', 'M', 'I', 'N', 'G']

Printing all elements using slice operation:


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

Negative index List slicing:


# Creating a List
List = ['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'R', 'A', 'M', 'M', 'I',
'N', 'G']
print("Initial List: ")
print(List)

# Print elements from beginning


# to a pre-defined point using Slice
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last: ")
print(Sliced_List)

# Print elements of a range


# using negative index List slicing
Sliced_List = List[-6:-1]
print("\nElements sliced from index -6 to -1")
print(Sliced_List)

# Printing elements in reverse


# using Slice operation
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

Output:
Initial List:
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'R', 'A', 'M', 'M', 'I', 'N',
'G']

Elements sliced till 6th element from last:


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

Elements sliced from index -6 to -1


['A', 'M', 'M', 'I', 'N']

Printing List in reverse:


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

Looping through a list in Python:


Looping through a list in Python can be done using various constructs, with the most common
ones being the for loop and list comprehension. I'll provide examples for both:

1. Using a for loop:


You can use a for loop to iterate over each element in the list and perform actions on each
item.
my_list = [1, 2, 3, 4, 5]

for item in my_list:


print(item)

This will print each item in the list on a new line.

2. Using list comprehension:


List Comprehension:
Python List comprehensions are used for creating new lists from other iterables like tuples,
strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression,
which is executed for each element along with the for loop to iterate over each element.

Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example 1:
# Python program to demonstrate list comprehension in Python

# below list contains square of all numbers from range 1 to 10


square = [x ** 2 for x in range(1, 11)]
print(square)

Output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Example 2:
List = [1, 5, 3, 4, 5, 5, 6, 7, 5, 9, 10, 11, 12]
# below list contains square of all even numbers
even_square_list = [x**2 for x in List if x % 2 == 0]
print(even_square_list)

Output:
[16, 36, 100, 144]

Example 3: To take multiple inputs from user and convert them into Integers using list
comprehension:
lst = input("Enter list of numbers: ").split()
# Numbers present in string form
print(lst)
data = [int(x) for x in lst]
# Numbers present in Integer form
print(data)
Output:
Enter list of numbers: 1 2 3 4 5
[1, 2, 3, 4, 5]

Mutability of Lists in Python:

In Python, lists are mutable, which means that you can modify the elements of a list after it
has been created. This mutability allows you to change, add, or remove elements in a list.
Here are some common operations that demonstrate the mutability of lists:
1. Changing an element:
You can change an element at a specific index in a list.
my_list = [10, 20, 30]
my_list[1] = 25 # Change the element at index 1 to 25
print(my_list) # Output: [10, 25, 30]

2. Adding elements:
You can add elements to the end of a list using the append() method or insert elements at a
specific index using the insert() method.
my_list = [10, 20, 30]
my_list.append(40) # Add 40 to the end of the list
print(my_list) # Output: [10, 20, 30, 40]
my_list.insert(1, 15) # Insert 15 at index 1
print(my_list) # Output: [10, 15, 20, 30, 40]

3. Removing elements:
You can remove elements by their value using the remove() method, or by their index using
the pop() method:
my_list = [10, 20, 30, 40]
my_list.remove(30) # Remove the element with value 30
print(my_list) # Output: [10, 20, 40]

popped_value = my_list.pop(1) # Remove and return the element at index 1


print(my_list) # Output: [10, 40]
print(popped_value) # Output: 20

These operations demonstrate the mutability of lists, allowing you to modify their content
during program execution.

list methods:
Function Description
append() Add an element to the end of the list
extend() Add all elements of a list to another list
insert() Insert an item at the defined index
remove() Removes an item from the list
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
pop() Removes and returns the item at the specified index. If no index is
provided, it removes and returns the last item.

Tuples in Python
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple
can be of any type, and they are indexed by integers.
Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is
more common to define a tuple by closing the sequence of values in parentheses. This helps
in understanding the Python tuples more easily.

Creating a Tuple:
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping the data sequence.
Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing.

Example: Python program to demonstrate the addition of elements in a Tuple.


# Creating an empty Tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple
# with the use of string
Tuple1 = ('Python', 'Programming')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Python')
print("\nTuple with the use of function: ")
print(Tuple1)

Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Python', 'Programming')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('P', 'y', 't', 'h', 'o', 'n')

Creating a Tuple with Mixed Datatypes:


Tuples can contain any number of elements and of any datatype (like strings, integers, list,
etc.). Tuples can also be created with a single element, but it is a bit tricky. Having one element
in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# Creating a Tuple with Mixed Datatype
Tuple1 = (5, 'Welcome', 7, 'Hello', True, 0.0)
print("\nTuple with Mixed Datatypes: ")
print(Tuple1)

Output:
Tuple with Mixed Datatypes:
(5, 'Welcome', 7, 'Hello', True, 0.0)

Accessing of Tuples:
Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that
are accessed via unpacking or indexing (or even by attribute in the case of named tuples).
Lists are mutable, and their elements are usually homogeneous and are accessed by iterating
over the list.
Note: In unpacking of tuple number of variables on the left-hand side should be equal to a
number of values in given tuple a.

# Accessing Tuple with Indexing


Tuple1 = tuple("Welcome")
print("\nFirst element of Tuple: ")
print(Tuple1[0])

# Tuple unpacking
Tuple1 = ("This", "Is", "Tuple")

# This line unpack


# values of Tuple1
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)

Output:
First element of Tuple:
W

Values after unpacking:


This
Is
Tuple

Tuple as Return Value in functions:


In Python, you can return a tuple as a return value from a function. A tuple is an ordered
collection of elements, similar to a list, but unlike lists, tuples are immutable, meaning their
elements cannot be modified once they are created. Here's how you can use a tuple as a
return value in a function:
def return_tuple():
# Create a tuple
my_tuple = (1, 2, 3)
return my_tuple

# Call the function and receive the returned tuple


result_tuple = return_tuple()

# Print the tuple


print(result_tuple) # Output: (1, 2, 3)

You can also return multiple values as a tuple from a function:


def return_multiple_values():
value1 = 10
value2 = 'hello'
return value1, value2

# Call the function and receive the returned tuple


result_tuple = return_multiple_values()

# Print the tuple


print(result_tuple) # Output: (10, 'hello', [1, 2, 3])

# Access individual elements of the tuple


print(result_tuple[0]) # Output: 10
print(result_tuple[1]) # Output: hello
Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple
gets deleted by the use of del() method.
Note- Printing of Tuple after deletion results in an Error.
# Deleting a Tuple

Tuple1 = (0, 1, 2, 3, 4)
del Tuple1

print(Tuple1) # Error

Difference between List and Tuple:


In Python, lists and tuples are both collection data types, but they have key differences in
terms of mutability, syntax, and intended use. Here are the main differences between lists
and tuples:
1. Mutability:
● Lists are mutable, meaning you can modify their elements after creation. You
can add, remove, or change elements within a list.
● Tuples are immutable, meaning their elements cannot be modified after
creation. Once a tuple is created, you cannot change its elements.
2. Syntax:
● Lists are defined using square brackets []. Elements are separated by commas
and can be of any data type, including mixed types.
● Tuples are defined using parentheses (). Elements are also separated by
commas, and a tuple can contain elements of any data type.
3. Use Cases:
● Lists are commonly used when you need a collection of elements that can be
modified, such as when you want to store a sequence of related items, and
you might need to add or remove items as the program runs.
● Tuples are often used when you want to store related pieces of data that
should not be modified, such as coordinates, configuration settings, or a fixed
set of values that represent an entity.

4. Performance:
● Tuples are generally more lightweight and efficient in terms of memory and
performance compared to lists because of their immutability. This can make
tuples a better choice for situations where the data doesn't need to change.
Note: In summary, use lists when you need a mutable collection of items, and use tuples when
you need an immutable collection or want to ensure data integrity.

Sets in Python
In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements. The major advantage of using a set, as opposed to a list, is that it has a
highly optimized method for checking whether a specific element is contained in the set.

Creating a Set:
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by a ‘comma’.
Note: A set cannot have mutable elements like a list, as it is mutable.
Example:
# Python program to demonstrate Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with the use of a String


set1 = set("Python")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with the use of Constructor Using object to Store String
String = 'Python'
set1 = set(String)
print("\nSet with the use of an Object: " )
print(set1)

# Creating a Set with the use of a List


set1 = set(["Python", "For", "Beginners"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with the use of a tuple


t=("Python", "For", "Beginners")
print("\nSet with the use of Tuple: ")
print(set(t))

Output:
Initial blank Set:
set()

Set with the use of String:


{'y', 't', 'h', 'n', 'P', 'o'}

Set with the use of an Object:


{'y', 't', 'h', 'n', 'P', 'o'}

Set with the use of List:


{'Beginners', 'For', 'Python'}

Set with the use of Tuple:


{'Beginners', 'For', 'Python'}

Creating a set with another method


# Another Method to create sets
# Set containing numbers
my_set = {1, 2, 3}
print(my_set) # {1, 2, 3}
Set functions:

Adding Elements to a Set:


1. Using add() method
Elements can be added to the Set by using the built-in add() function. Only one element at a
time can be added to the set by using add() method, loops are used to add multiple elements
at a time with the use of add() method.

Note: Lists cannot be added to a set as elements because Lists are mutable whereas Tuples
can be added because tuples are immutable.

# Python program to demonstrate Addition of elements in a Set

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Adding element and tuple to the Set


[Link](8)
[Link](9)
[Link]((6, 7))
print("\nSet after Addition of Three elements: ")
print(set1)

# Adding elements to the Set


# using Iterator
for i in range(1, 6):
[Link](i)
print("\nSet after Addition of elements from 1-5: ")
print(set1)

Output:
Initial blank Set:
set()

Set after Addition of Three elements:


{8, 9, (6, 7)}

Set after Addition of elements from 1-5:


{1, 2, 3, 4, 5, 8, 9, (6, 7)}

2. Using update() method:


For the addition of two or more elements Update() method is used. The update() method
accepts lists, strings, tuples as well as other sets as its arguments. In all of these cases,
duplicate elements are avoided.
# Python program to demonstrate Addition of elements in a Set

# Addition of elements to the Set


# using Update function
set1 = set([4, 5, (6, 7)])
[Link]([10, 11])
print("\nSet after Addition of elements using Update: ")
print(set1)
Output:
Set after Addition of elements using Update:
{4, 5, 10, 11, (6, 7)}

# Python program to demonstrate Accessing of elements in a set

# Creating a set
set1 = set(["Python", "For", "Beginners"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")

# Checking the element


# using in keyword
print("\n")
print("For" in set1)

Output:
Initial set
{'For', 'Beginners', 'Python'}

Elements of set:
For Beginners Python

True

Removing elements from the Set:


1. Using remove() method or discard() method:
Elements can be removed from the Set by using the built-in remove() function but a KeyError
arises if the element doesn’t exist in the set. To remove elements from a set without KeyError,
use discard(), if the element doesn’t exist in the set, it remains unchanged.

# Python program to demonstrate Deletion of elements in a Set

# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)

# Removing elements from Set using Remove() method


[Link](5)
[Link](6)
print("\nSet after Removal of two elements: ")
print(set1)

# Removing elements from Set using Discard() method


[Link](8)
[Link](9)
print("\nSet after Discarding two elements: ")
print(set1)

# Removing elements from Set using iterator method


for i in range(1, 5):
[Link](i)
print("\nSet after Removing a range of elements: ")
print(set1)

Output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after Removal of two elements:


{1, 2, 3, 4, 7, 8, 9, 10, 11, 12}

Set after Discarding two elements:


{1, 2, 3, 4, 7, 10, 11, 12}

Set after Removing a range of elements:


{7, 10, 11, 12}

2. Using pop() method:


Pop() function can also be used to remove and return an element from the set, but it removes
only the last element of the set.
Note: If the set is unordered then there’s no such way to determine which element is popped
by using the pop() function.

# Python program to demonstrate Deletion of elements in a Set

# Creating a Set
set1 = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1)

# Removing element from the


# Set using the pop() method
[Link]()
print("\nSet after popping an element: ")
print(set1)

Output:
Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

Set after popping an element:


{2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

3. Using clear() method:


To remove all the elements from the set, clear() function is used.
#Creating a set
set1 = set([1,2,3,4,5])
print("\n Initial set: ")
print(set1)
# Removing all the elements from
# Set using clear() method
[Link]()
print("\nSet after clearing all the elements: ")
print(set1)

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

Set after clearing all the elements:


set()

Typecasting Objects into sets:


# Typecasting Objects in Python3 into sets

# Typecasting list into set


my_list = [1, 2, 3, 3, 4, 5, 5, 6, 2]
my_set = set(my_list)
print("my_list as a set: ", my_set)

# Typecasting string into set


my_str = "Python Programming"
my_set1 = set(my_str)
print("my_str as a set: ", my_set1)

Output:
my_list as a set: {1, 2, 3, 4, 5, 6}
my_str as a set: {'y', 'n', 't', 'o', 'r', 'h', 'g', 'm', 'P', 'a', ' ',
'i'}

Advantages of using Sets:


● Unique Elements: Sets can only contain unique elements, so they can be useful for
removing duplicates from a collection of data.
● Fast Membership Testing: Sets are optimized for fast membership testing, so they can
be useful for determining whether a value is in a collection or not.
● Mathematical Set Operations: Sets support mathematical set operations like union,
intersection, and difference, which can be useful for working with sets of data.
● Mutable: Sets are mutable, which means that you can add or remove elements from
a set after it has been created.
Disadvantages of using Sets:
● Unordered: Sets are unordered, which means that you cannot rely on the order of the
data in the set. This can make it difficult to access or process data in a specific order.
● Limited Functionality: Sets have limited functionality compared to lists, as they do not
support methods like append() or pop(). This can make it more difficult to modify or
manipulate data stored in a set.
● Memory Usage: Sets can consume more memory than lists, especially for small
datasets. This is because each element in a set requires additional memory to store a
hash value.
● Less Commonly Used: Sets are less commonly used than lists and dictionaries in
Python, which means that there may be fewer resources or libraries available for
working with them.

Dictionary in Python
Dictionary in Python is a collection of keys values, used to store data values like a map, which,
unlike other data types which hold only a single value as an element.
Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it more
optimized.

Example:
Dict = {1: One, 2: Two, 3: Three}
print(Dict) # {1: One, 2: Two, 3: Three}

In Python, a dictionary can be created by placing a sequence of elements within curly {}


braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its Key:value. Values in a dictionary can be of any
data type and can be duplicated, whereas keys can’t be repeated and must be immutable.

Note –
● Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.
● 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: 'One', 2: 'Two', 3: 'Three'})
print("\nDictionary with the use of dict(): ")
print(Dict)
Output:

Output:
Empty Dictionary:
{}

Dictionary with the use of dict():


{1: 'One', 2: 'Two', 3: 'Three'}

Adding elements to a Dictionary:


Addition of elements can be done in multiple ways. One value at a time can be added to a
Dictionary by defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing
value in a Dictionary can be done by using the built-in update() method. Nested key values
can also be added to an existing Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise
a new Key with the value is added to the Dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Python'
Dict[2] = 'Java'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# to a single Key
Dict['Value_set'] = {2, 3, 4}
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

Output:
Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Python', 2: 'Java', 3: 1}

Dictionary after adding 3 elements:


{0: 'Python', 2: 'Java', 3: 1, 'Value_set': {2, 3, 4}}

Updated key value:


{0: 'Python', 2: 'Welcome', 3: 1, 'Value_set': {2, 3, 4}}

Accessing elements of 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: 'One', 'two': 2, 3: 'Three'}

# accessing a element using key


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

# accessing a element using key


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

Output:
Accessing a element using key:
2
Accessing a element using key:
One

There is also a method called get() that will also help in accessing the element from a
dictionary. This method accepts key as argument and returns the value.

# Python program to demonstrate accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'One', 'two': 2, 3: 'Three'}

# accessing a element using get


print("Accessing a element using get:")
print([Link]('two'))

Output:
Accessing a element using get:
2

Deleting Elements using del Keyword:


The items of the dictionary can be deleted by using the del keyword as given below.
# Python program to demonstrate
# Deleting Elements using del Keyword

# Creating a Dictionary
Dict = {1: 'One', 'two': 2, 3: 'Three'}

print("Dictionary =")
print(Dict)
#Deleting some of the Dictionary data
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)

Output:
Dictionary =
{1: 'One', 'two': 2, 3: 'Three'}
Data after deletion Dictionary=
{'two': 2, 3: 'Three'}

Dictionary operations and methods:


Method Description
[Link]() Remove all the elements from the dictionary
[Link]() Returns a copy of the dictionary
[Link](key, default = “None”) Returns the value of specified key
[Link]() Returns a list containing a tuple for each key value pair
[Link]() Returns a list containing dictionary’s keys
[Link](dict2) Updates dictionary with specified key-value pairs
[Link]() Returns a list of all the values of dictionary
pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
Example:
# demo for all dictionary methods
dict1 = {1: "Python", 2: "Java", 3: "C++", 4: "PHP"}

# copy() method
dict2 = [Link]()
print(dict2)

# clear() method
[Link]()
print(dict1)

# get() method
print([Link](1))

# items() method
print([Link]())

# keys() method
print([Link]())

# pop() method
[Link](4)
print(dict2)

# popitem() method
[Link]()
print(dict2)

# update() method
[Link]({3: "Scala"})
print(dict2)

# values() method
print([Link]())

Output:
{1: 'Python', 2: 'Java', 3: 'C++', 4: 'PHP'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'C++'), (4, 'PHP')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'C++'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])

Illustrative Programs:

1. Selection sort:
Selection sort is a simple sorting algorithm that repeatedly selects the minimum element from
an unsorted portion of the list and moves it to the beginning of the sorted portion. Here's a
Python implementation of selection sort:
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
# Find the index of the minimum element in the unsorted portion
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j

# Swap the minimum element with the current element (if they are not
the same)
if min_index != i:
arr[i], arr[min_index] = arr[min_index], arr[i]

# Example usage:
my_list = [64, 25, 12, 22, 11]
print("Original list is, ", my_list)
selection_sort(my_list)
print("Sorted list:", my_list)

Output:
Original list is, [64, 25, 12, 22, 11]
Sorted list: [11, 12, 22, 25, 64]

In the example above, selection_sort sorts the input list arr in ascending order. It iterates
through the list, maintaining the current position i as the starting point for the unsorted
portion. It then iterates through the remaining unsorted portion to find the index of the
minimum element. Once the minimum element is found, it is swapped with the current
element at index i. This process continues until the entire list is sorted.

2. Insertion sort:
Insertion sort is a simple sorting algorithm that builds the final sorted list one element at a
time. It works by taking an element from the unsorted portion of the list and inserting it into
its correct position in the sorted portion of the list. Here's a Python implementation of
insertion sort:
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1

while j >= 0 and key < arr[j]:


arr[j + 1] = arr[j]
j -= 1

arr[j + 1] = key

# Example usage:
my_list = [64, 34, 25, 12, 22, 11, 90]
print("Original list:", my_list)
insertion_sort(my_list)
print("Sorted list:", my_list)

Output:
Original list: [64, 34, 25, 12, 22, 11, 90]
Sorted list: [11, 12, 22, 25, 34, 64, 90]

In this example, insertion_sort sorts the input list arr in ascending order. It starts with the
second element (index 1) and iterates through the list, considering each element one at a
time. It compares the current element to the elements in the sorted portion of the list and
shifts the larger elements to the right to make space for the current element. Once the correct
position for the current element is found, it is inserted there.

3. Merge sort:
Merge sort is a popular and efficient comparison-based sorting algorithm that uses a divide-
and-conquer approach to sort a list. It breaks the list into smaller, more manageable sublists,
sorts each sublist, and then combines them back together. Here's a Python implementation
of merge sort:
def merge_sort(arr):
# Check if the list has more than one element
if len(arr) > 1:
# Calculate the midpoint of the list
mid = len(arr) // 2

# Divide the list into two halves


left_half = arr[:mid]
right_half = arr[mid:]

# Recursively sort both halves


merge_sort(left_half)
merge_sort(right_half)

# Initialize pointers for the left and right halves and the main list
i = j = k = 0

# Merge the sorted halves back together


while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

# Copy any remaining elements from the left half


while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1

# Copy any remaining elements from the right half


while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1

# Example usage:
my_list = [38, 27, 43, 3, 9, 82, 10]
print("Original list:", my_list)
merge_sort(my_list)
print("Sorted list:", my_list)

Output:
Original list: [38, 27, 43, 3, 9, 82, 10]
Sorted list: [3, 9, 10, 27, 38, 43, 82]

You might also like