UNIT II
Python has a set of built-in methods that you can use on lists.
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 item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python list slicing
List slicing in Python allows you to extract specific portions of a list using the syntax
list_name[start : end : step]
It is a powerful tool for accessing, modifying, or creating subsets of lists.
Python List Slicing Syntax
list_name[start : end : step]
Parameters:
start (optional): Index to begin the slice (inclusive). Defaults to 0 if
omitted.
end (optional): Index to end the slice (exclusive). Defaults to the length of
list if omitted.
step (optional): Step size, specifying the interval between elements.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[::])
print(a[:])
output:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Get all items before/after a specific position
To get all the items from a specific position to the end of the list, we can
specify the start index and leave the end blank.
To get all the items before a specific index, we can specify the end index while
leaving start blank.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[2:]
print(b)
c = a[:3]
print(c)
output:
[3, 4, 5, 6, 7, 8, 9]
[1, 2, 3]
Get items at specified intervals
To extract elements at specific intervals, use the step parameter.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[::1]
print(b)
c = a[1:8:3]
print(c)
output:
[1, 3, 5, 7, 9]
[2, 5, 8]
Out-of-bound slicing
In Python, list slicing allows out-of-bound indexing without raising errors. If we specify
indices beyond the list length then it will simply return the available items.
Example: The slice a[7:15] starts at index 7 and attempts to reach index 15, but since the list
ends at index 8, so it will return only the available elements (i.e. [8,9]).
Negative Indexing
Negative indexing is useful for accessing elements from the end of the list.
The last element has an index of -1, the second last element -2, and so on.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[-2:]
print(b)
c = a[:-3]
print(c)
d = a[-4:-1]
print(d)
e = a[-8:-1:2]
print(e)
Output
[8, 9]
[1, 2, 3, 4, 5, 6]
[6, 7, 8]
[2, 4, 6, 8]
Reverse a list using slicing
In this example, we’ll reverse the entire list using a slicing trick. By using a negative step value,
we can move through the list in reverse order.
Python
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = a[::-1]
print(b)
output:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
What is list cloning?
In Python, “cloning a list” means creating a new list object that has the same elements as an
existing list. The cloned list is a separate entity from the original list, meaning any modifications
made to one list do not affect the other. Cloning allows you to create a copy of a list to work with
independently, preserving the original list in its original state.
Using list slicing technique
Slicing technique in python is used to access a range of items in a list. This technique can also
be used for cloning a list, where we want to modify a list and also keep a copy of the original.
Syntax
list_obj[start:stop:step]
l1 = [1,2,3,4]
l2= l1[:]
print("Original List:", l1)
("After Cloning:", l2)
print("ID of Original list", id(l1))
print("ID of copied list", id(l2))
[Link](10)
print('Original list',l1)
print('Copied and updated list',l2)
Original List: [1, 2, 3, 4]
After Cloning: [1, 2, 3, 4]
ID of Original list 140565661890112
ID of copied list 140565795507408
Original list [1, 2, 3, 4]
Copied and updated list [1, 2, 3, 4, 10]
Using copy() method
The copy() is a Python list method which is used to get a shallow copy of the list. It means if we
do any modification of the new list and those changes will not be reflected on the original list.
Syntax
new_list = [Link]()
l1 = [1,2,3,4]
l2 = [Link]()
print("Original List:", l1)
print("After Cloning:", l2)
print("ID of Original list", id(l1))
print("ID of copied list", id(l2))
[Link](10)
print('Original list',l1)
print('Copied and updated list',l2)
Output
Original List: [1, 2, 3, 4]
After Cloning: [1, 2, 3, 4]
ID of Original list 140565661915808
ID of copied list 140565661713424
Original list [1, 2, 3, 4]
Copied and updated list [1, 2, 3, 4, 10]
Using the list() method
The list() method is also considered as the simplest way of cloning a list. This function creates a
new list object. Let’s take an example and see how the list() method clones a python list.
l1 = [1,2,3,4]
l2 = list(l1)
print("Original List:", l1)
print("After Cloning:", l2)
print("ID of Original list", id(l1))
print("ID of copied list", id(l2))
[Link](10)
print('Original list',l1)
print('Copied and updated list',l2)
output:
Original List: [1, 2, 3, 4]
After Cloning: [1, 2, 3, 4]
ID of Original list 140565661915808
ID of copied list 140565661713424
Original list [1, 2, 3, 4]
Copied and updated list [1, 2, 3, 4, 10]
Nested list
A nested list in Python is simply a list that contains other lists as its elements.
This structure allows for representing multi-dimensional data, such as matrices or
tables.
Here’s an example:
nested_list = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
In this example, nested_list is a list of lists, where each inner list contains integers.
Accessing Elements
We can access elements in a nested list using multiple indices. The first index
refers to the outer list, and the second index refers to the inner list.
# Accessing the first element of the first sublist
print(nested_list[0][0])
Output: 1
# Accessing the second element of the third sublist
print(nested_list[2][2])
Output: 8
Iterating through a Nested List
We can loop through a nested list using loops. Here’s an example of iterating
through both the outer and inner lists:
for sublist in nested_list:
for item in sublist:
print(item)
This will output:
Output:
1
2
3
4
5
6
7
8
9
Modifying Elements
We can modify elements in a nested list by specifying their indices:
# Change the first element of the second sublist
nested_list[1][0] = 40
print(nested_list)
Output: [[1, 2, 3],
[40, 5, 6],
[7, 8, 9]]
2. Lists with Different Lengths: A nested list does not require all inner lists to have the same
length. This gives you flexibility in storing data of different shapes.
uneven_nested_list = [
[1, 2],
[3, 4, 5],
[6]
]
print(uneven_nested_list)
Output: [[1, 2], [3, 4, 5], [6]]
TUPLE
A tuple in Python is an ordered, immutable collection of items. Like lists, tuples can store
multiple elements of different data types, but unlike lists, once a tuple is created, its elements
cannot be modified (i.e., tuples are immutable). Tuples are often used when you want to ensure
that the data cannot be changed after creation. Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value
Syntax for Creating a Tuple
Tuples are created by placing a comma-separated sequence of values inside parentheses ().
A basic tuple
my_tuple = (1, 2, 3)
A tuple with mixed data types
mixed_tuple = (1, "hello", 3.14, True)
A tuple with a single element (note the trailing comma)
element_tuple = (5,)
Accessing Elements
We can access elements of a tuple by using indexing, similar to lists. Indexing starts at 0.
Accessing elements using index
print(my_tuple[0])
Output: 1
print(mixed_tuple[1])
Output: "hello"
we can also use negative indexing to access elements from the end:
print(my_tuple[-1])
Output: 3 (last element)
Updating an element in tuple
1. Reassigning Entire Tuple
The simplest way to "update" a tuple is by reassigning it entirely. Since tuples are immutable, to
change any value, we’ll need to create a new tuple with the updated values.
Python
tup = (1, 2, 3, 4)
tup1 = (10, 2, 3, 4)
print(tup1)
Output
(10, 2, 3, 4)
Explanation:
The original tuple (1, 2, 3, 4) is reassigned to (10, 2, 3, 4), effectively "updating" the
tuple.
[Link] Tuples by Concatenation
You can create a new tuple by concatenating parts of the original tuple along with
new elements.
Python
1
tup1 = (1, 2, 3, 4)
3
tup2 = (10,) + tup1[]
6
print(tup2)
Output
(10, 2, 3, 4)
Explanation:
We take the first element (10,) and concatenate it with the rest of the
original tuple .
This creates a new tuple with the updated value.
[Link] a List to Modify the Tuple
The most straightforward way to update a tuple is to convert it into a list,
change the list, and convert it back to a tuple. Lists in Python are mutable, making
them easy to modify.
tup1 = (1, 2, 3, 4)
li = list(tup1)
[Link](5)
li[1] = 'a'
tup2 = tuple(li)
print(tup2)
Output
(1, 'a', 3, 4, 5)
Explanation:
We first convert the tuple into a list using list(tup1).
Then, we modify the list by updating the element at index 0.
Finally, we convert the list back into a tuple using tuple(li).
[Link] Tuple Unpacking
Tuple unpacking can be used to extract parts of a tuple and modify specific elements
without changing the entire tuple.
Python
# Original tuple
tup1 = (1, 2, 3, 4)
a, b, c, d = tup1
b = 10
tup2 = (a, b, c, d)
print(tup2)
Output
(1, 10, 3, 4)
Explanation:
We use tuple unpacking to extract the elements of the tuple into variables a, b,
c, and d.
Then we update b to 10 and create a new tuple with the updated value.
Deleting an element in tuple
It is not possible to directly "delete" an item from a
Python tuple because tuples are immutable. Once a tuple is created, its
elements cannot be changed, added, or removed.
To achieve a result that looks like item deletion, you must create
a new tuple that contains all the elements of the original except the one
you want to remove. There are two primary methods for this:
a. Convert to a List, Modify, and Convert Back
b. Create a New Tuple Using Slicing operation
Convert to a List, Modify, and Convert Back
my_tuple = ("apple", "banana", "cherry", "date")
temp_list = list(my_tuple)
temp_list.remove("banana")
my_tuple = tuple(temp_list)
print(my_tuple)
Output: ('apple', 'cherry', 'date')
Removing an item in Tuple Using Slicing
my_tuple = (10, 20, 30, 40)
new_tuple = my_tuple[2:]
print(new_tuple)
Output: (20, 30, 40)
NESTED TUPLE:
A nested tuple is a Python tuple that has been placed inside of another tuple.
Let's have a look at the following 8-element tuple.
tuple = (12, 23, 36, 20, 51, 40, (200, 240, 100))
This last element, which consists of three items enclosed in parenthesis, is known
as a nested tuple since it is contained inside another tuple. The name of the main
tuple with the index value, tuple[index], can be used to obtain the nested tuple, and
we can access each item of the nested tuple by using tuple[index-1][index-2]
Creating a nested tuple of one element only
employee = ((10, "Ram", 13000),)
print(employee)
Creating a multiple-value nested tuple
employee = ((10, "RAM", 13000), (24, "Harry", 15294), (15, "GEETHA", 2000
1), (40, "PETER", 16395))
print(employee)
Output:
((10, 'RAM', 13000), (24, 'Harry', 15294), (15, 'GEETHA', 20001), (40, 'PETER',
16395))
mytuple = (2, 4, (8, 7, 30), 6, 220)
print("Tuple:", mytuple)
print("Length of Tuple:", len(mytuple))
OUTPUT
Tuple: (2, 4, (8, 7, 30), 6, 220)
Length of Tuple: 5
Accessing Elements in a Nested Tuple
mytuple = ("php", ".NET", ("python", "java", "c++"), "learning")
print("Inner Tuple:", mytuple[2])
print("First Element of Inner Tuple:", mytuple[2][0])
OUTPUT
Inner Tuple: ('python', 'java', 'c++')
First Element of Inner Tuple: python
Deleting an Element:
data = (('dog', 30), ('cat', 20), ('bird', 10))
data = tuple(item for item in data if item[0] != 'bird')
print(data)
OUTPUT
(('dog', 30), ('cat', 20))
Sorting in Python Tuple Within A Tuple
In this example, the original tuple of tuples named data is defined with elements
('dog', 30), ('cat', 20), ('bird', 10), and ('fish', 25). The program uses
the sorted() function to sort the tuples based on their second element (quantity) in
ascending order. The resulting modified tuple is then printed using print(data).
data = (('dog', 30), ('cat', 20), ('bird', 10))
data = tuple(sorted(data, key=lambda x: x[1]))
print(data)
OUTPUT
(('bird', 10), ('cat', 20), ('dog', 30))
DICTIONARY
In Python, a dictionary is a built-in data structure that stores data in key–value
pairs. A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Syntax:
{
<key_1>: <value_1>,
<key_2>: <value_2>,
...,
<key_N>: <value_N>,
}
Characteristics of Dictionary
Stores data in key : value format
Keys must be unique
Values can be duplicated
Dictionary is mutable (can be changed)
Keys must be immutable (string, number, tuple)
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Using dict():
d = dict(name="Ram", age=21)
Accessing Items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
OUTPUT:
Mustang
Using get()
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("model")
print(x)
OUTPUT:
Mustang
The keys() method will return a list of all the keys in the dictionary.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
OUTPUT:
dict_keys(['brand', 'model', 'year'])
Check if Key Exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Adding and Modifying Items in Dictionary
Adding an Item to a Dictionary
A new item can be added to a dictionary by assigning a new key with a value.
Syntax
dictionary_name[new_key] = value
Example
student = {"name": "Ram",
"age": 20
}
student["course"] = "Data Science"
print(student)
Output
{'name': 'Ram', 'age': 20, 'course': 'Data Science'}
Modifying an Item in a Dictionary
An existing item can be modified by assigning a new value to an existing key.
Syntax
dictionary_name[existing_key] = new_value
Example
student["age"] = 21
print(student)
OUTPUT
{'name': 'Ram', 'age': 21, 'course': 'Data Science'}
Adding or Modifying Using update() Method
The update() method can add multiple items or modify existing ones.
[Link]({"age": 22, "college": "ABC College"})
Deleting an Item in Dictionary
In Python, items can be deleted from a dictionary using built-in statements and
methods.
1. Using del Statement
Deletes a specific key-value pair.
Syntax
del dictionary_name[key]
student = {"name": "Ram", "age": 20, "course": "Data Science"}
del student["age"]
print(student)
Removes the key age
2. Using pop() Method
Removes a specific item and returns its value.
Syntax
dictionary_name.pop(key)
Example
[Link]("course")
Using popitem() Method
Removes the last inserted key-value pair.
Example
[Link]()
Using clear() Method
Removes all items from the dictionary.
[Link]()
Sorting Items in Dictionary (Python)
A dictionary in Python is unordered, so items are not stored in sorted order.
However, we can sort dictionary items using keys(), values(), or items() along with
the sorted() function.
1. Sorting Dictionary by Keys
Syntax
sorted(dictionary_name)
Example
student = {"name": "Sathya", "age": 21, "course": "Data Science"}
sorted_keys = sorted(student)
print(sorted_keys)
OUTPUT
['age', 'course', 'name']
Returns sorted list of keys
2. Sorting Dictionary by Values
Syntax
sorted(dictionary_name.values())
Example
marks = {"Maths": 85, "Science": 90, "English": 78}
sorted_values = sorted([Link]())
print(sorted_values)
Output
[78, 85, 90]
Returns sorted list of values
3. Sorting Dictionary Items (Key-Value Pairs)By Keys
sorted_items = sorted([Link]())
print(sorted_items)
Example
Output
[('age', 21), ('course', 'Data Science'), ('name', 'Sathya')]
[Link] Values (Using lambda)
sorted_items = sorted([Link](), key=lambda x: x[1])
print(sorted_items)
Output
("English": 78,"Maths": 85, "Science": 90)
5. Sorting in Reverse Order
sorted_desc = dict(sorted([Link](), reverse=True))
It will sort the dictionary in ascending order
Output
Science 75
Maths 80
English 85
Looping Over a Dictionary in Python
Looping is used to traverse keys, values, or key–value pairs in a dictionary.
Useful when only keys are required
1. Looping Through Keys
for key in dictionary:
print(key)
Example
student = {"name": "Ram", "age": 20, "course": "Data Science"}
for key in student:
print(key)
Prints only keys
Output
name
age
course
[Link] Through Values Using values()
values() returns only the values
Keys are not accessible in this loop
for value in [Link]():
print(value)
Output
Ram
20
Python
3. Looping Through Key–Value Pairs Using items()
items() returns both key and value as pairs
Most commonly used method
Example
for key, value in [Link]():
print(key, ":", value)
Output
name : Ram
age : 20
course : Python
4. Looping Using Index
Dictionaries do not support indexing
Must convert keys to list (less efficient)
Example
keys = list([Link]())
for i in range(len(keys)):
print(keys[i], ":", student[keys[i]])
Output
name : Ram
age : 20
course : Python
Cloning List in Python
Definition
Cloning a list means creating a new list with the same elements as an existing list.
The cloned list is a separate copy, so changes made to one list do not affect the
other.
Cloning is Needed
To avoid unwanted changes in the original list
To work safely with data
To maintain data integrity
Common in data processing and algorithms
Methods of Cloning a List
1. Using Assignment Operator (=)
[Link] does not create a real clone.
[Link] variables refer to the same list in memory (shallow reference).
Example
list1 = [1, 2, 3]
list2 = list1
[Link](4)
print(list1)
print(list2)
Output
[1, 2, 3, 4]
[1, 2, 3, 4]
2. Using copy() Method
[Link] a shallow copy of the list.
[Link] in the cloned list do not affect the original list.
Example
list1 = [1, 2, 3]
list2 = [Link]()
[Link](4)
print(list1)
print(list2)
Output
[1, 2, 3]
[1, 2, 3, 4]
3. Using Slicing ([:])
[Link] copies all elements into a new list.
[Link] is a simple and commonly used cloning method.
Example
list1 = [10, 20, 30]
list2 = list1[:]
[Link](20)
print(list1)
print(list2)
Output
[10, 20, 30]
[10, 30]
4. Using list() Constructor
The list() constructor creates a new list from an existing list.
Example
list1 = ['a', 'b', 'c']
list2 = list(list1)
[Link]('d')
print(list1)
print(list2)
Output
['a', 'b', 'c']
['a', 'b', 'c', 'd']
[Link] deepcopy() (Advanced)
[Link] when lists contain nested lists.
[Link] a deep copy, copying all inner objects.
Example
import copy
list1 = [[1, 2], [3, 4]]
list2 = [Link](list1)
list2[0].append(99)
print(list1)
print(list2)
Output
[[1, 2], [3, 4]]
[[1, 2, 99], [3, 4]]
Best for nested lists
Mutability in List
Definition
A mutable object is one whose contents can be changed after creation.
In Python, lists are mutable.
List is Mutable
Elements can be added
Elements can be modified
Elements can be removed
Example: Modifying List Elements
a = [10, 20, 30]
a[1] = 99
print(a)
Output
[10, 99, 30]
✔ Value changed → list is mutable
Example: Adding Elements
a = [1, 2, 3]
[Link](4)
print(a)
Output
[1, 2, 3, 4]
Example: Removing Elements
a = [5, 6, 7]
[Link](6)
print(a)
Output
[5, 7]
Set in Python
Definition
A set in Python is an unordered, mutable collection of unique elements.
Sets do not allow duplicate values and are mainly used for membership testing
and mathematical operations. Creating a Set
Syntax
set_name = {element1, element2, element3}
Example
numbers = {1, 2, 3, 4}
print(numbers)
Output
{1, 2, 3, 4}
Creating Set Using set() Function
s = set([1, 2, 2, 3])
print(s)
Output
{1, 2, 3}
✔ Duplicate values are removed automatically
Adding Elements to a Set
Using add()
s = {1, 2, 3}
[Link](4)
print(s)
Output
{1, 2, 3, 4}
Using update()
[Link]([5, 6])
print(s)
Output
{1, 2, 3, 4, 5, 6}
Removing Elements from a Set
remove()
[Link](3)
print(s)
Output
{1, 2, 4, 5, 6}
❌ Error if element not found
discard()
[Link](10)
print(s)
Output
{1, 2, 4, 5, 6}
✔ No error if element not found