0% found this document useful (0 votes)
9 views28 pages

PP U3 Official Notes

This document provides an overview of lists in Python, detailing their characteristics, methods for creation, and various operations such as accessing elements, modifying lists, and using list comprehensions. It explains how lists can store mixed data types, are mutable, and maintain order, along with examples of common list methods like append, pop, and sort. Additionally, it covers advanced topics like list slicing, negative indexing, and passing lists as arguments to functions.

Uploaded by

bhusarisojval
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)
9 views28 pages

PP U3 Official Notes

This document provides an overview of lists in Python, detailing their characteristics, methods for creation, and various operations such as accessing elements, modifying lists, and using list comprehensions. It explains how lists can store mixed data types, are mutable, and maintain order, along with examples of common list methods like append, pop, and sort. Additionally, it covers advanced topics like list slicing, negative indexing, and passing lists as arguments to functions.

Uploaded by

bhusarisojval
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
You are on page 1/ 28

UNIT-3

LISTS, TUPLES, DICTIONARIES, STRINGS


LIST
A list in Python is a versatile and mutable data structure used to store an ordered
sequence of items. Lists are defined by enclosing comma-separated values within
square brackets [] and elements separated by commas.
A list may contain mixed type of items, this is possible because a list mainly stores
references at contiguous locations and actual items maybe stored at different
locations.
 List can contain duplicate items.
 List in Python are Mutable. Hence, we can modify, replace or delete the
items.
 List are ordered. It maintain the order of elements based on how they are
added.
 Accessing items in List can be done directly using their position (index),
starting from 0.
Example
# Empty list
x = []
a = [10, 20, "yash", 40, True]
print(a)
print(*a)

# Accessing elements using indexing


print(a[0]) # 10
print(a[1]) # 20
print(a[2]) # "yash"
print(a[3]) # 40
print(a[4]) # True

# Checking types of elements


print(type(a[2])) # str
print(type(a[4])) # bool
Output
[10, 20, 'yash', 40, True]
10 20 yash 40 True
10
20
yash
40
True
<class 'str'>
<class 'bool'>
Explanation:
 The list contains a mix of integers (10, 20, 40), a string (“yash”) and a
boolean (True).
 The list is printed and individual elements are accessed using their
indexes (starting from 0).
 type(a[2]) confirms “yash” is a str.
 type(a[4]) confirms True is a bool.

Note: Lists Store References, Not Values


Each element in a list is not stored directly inside the list structure. Instead, the list
stores references (pointers) to the actual objects in memory. Example (in above
figure).
 The list a itself is a container with references (addresses) to the actual
values.
 Python internally creates separate objects for 10, 20, “yash”, 40 and
True, then stores their memory addresses inside List a.
 This means that modifying an element doesn’t affect other elements but
can affect the referenced object if it is mutable
Creating a List
Here are some common methods to create a list:
1. Using Square Brackets
Example
# List of integers
a = [1, 2, 3, 4, 5]

# List of strings
b = ['apple', 'banana', 'cherry']

# Mixed data types


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

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
2. Using list() Constructor
We can also create a list by passing an iterable (like a string, tuple or
another list) to list() function.

Example
# From a tuple
a = list((1, 2, 3, 'apple', 4.5))
print(a)

Output
[1, 2, 3, 'apple', 4.5]
Creating List with Repeated Elements
We can create a list with repeated elements using the multiplication operator.
Example

a = [2] * 5 # Create a list [2, 2, 2, 2, 2]

b = [0] * 7 # Create a list [0, 0, 0, 0, 0, 0, 0]


print(a)
print(b)

Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]
Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start at 0,
so a[0] will access the first element, while negative indexing allows us to access
elements from the end of the list. Like index -1 represents the last elements of list.

Example
a = [10, 20, 30, 40, 50]

# Access first element


print(a[0])

# Access last element


print(a[-1])

Output
10
50
Different list methods in Python:
 append(): Adds an element to the end of the list.
 copy(): Returns a shallow copy of the list.
 clear(): Removes all elements from the list.
 count(): Returns the number of times a specified element appears in the
list.
 extend(): Adds elements from another list to the end of the current list.
 index(): Returns the index of the first occurrence of a specified
element.
 insert(): Inserts an element at a specified position.
 pop(): Removes and returns the element at the specified position (or the
last element if no index is specified).
 remove(): Removes the first occurrence of a specified element.
 reverse(): Reverses the order of the elements in the list.
 sort(): Sorts the list in ascending order (by default).

append():
Syntax: list_name.append(element)

Adds an element to the end of the list.


Example
a = [1, 2, 3]
a.append(4) # Add 4 to the end of the list
print(a)

Output
[1, 2, 3, 4]

copy():
Syntax: list_name.copy()

Returns a shallow copy of the list.


a = [1, 2, 3]
b = a.copy() # Create a copy of the list
print(b)

Output
[1, 2, 3]
clear():
Syntax: list_name.clear()

Removes all elements from the list.


a = [1, 2, 3]
a.clear() # Remove all elements from the list
print(a)

Output
[]

count():
Syntax: list_name.count(element)
Returns the number of times a specified element appears in the list.
a = [1, 2, 3, 2]
print(a.count(2)) # Count occurrences of 2 in the list

Output
2

extend():
Syntax: list_name.extend(iterable)
Adds elements from another list to the end of the current list.
a = [1, 2]
# Extend list a by adding elements from list [3, 4]
a.extend([3, 4])
print(a)

Output
[1, 2, 3, 4]
index():
Syntax: list_name.index(element)
Returns the index of the first occurrence of a specified element.
a = [1, 2, 3]
print(a.index(2)) # Find the index of 2 in the list

Output
1

insert():
Syntax: list_name.insert(index, element)
Inserts an element at a specified position.
a = [1, 3]
a.insert(1, 2) # Insert 2 at index 1
print(a)

Output
[1, 2, 3]
pop():
Syntax: list_name.pop(index)
Removes and returns the element at the specified position (or the last element if no
index is specified).
a = [1, 2, 3]
a.pop() # Remove and return the last element in the list
print(a)

Output
[1, 2]remove():

Syntax: list_name.remove(element)

Removes the first occurrence of a specified element.


a = [1, 2, 3]
a.remove(2) # Remove the first occurrence of 2
print(a)
Output
[1, 3]

reverse():
Syntax: list_name.reverse()
Reverse the order of the elements in the list.
a = [1, 2, 3]
a.reverse() # Reverse the list order
print(a)

Output
[3, 2, 1]

sort():
Syntax: list_name.sort(key=None, reverse=False)

Sorts the list in ascending order (by default).


a = [3, 1, 2]
a.sort() # Sort the list in ascending order
print(a)

Output
[1, 2, 3]
Iterating Over Lists
We can iterate the Lists easily by using a for loop or other iteration methods as
discussed earlier in for loop.

a = [1,2,'apple',45.78]

# Iterating over the list


for item in a:
print(item)
Output
1
2
apple
45.78

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.
Defaults to 1 if omitted

Examples : To get all the items from a list


a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[::]) # Get all elements in the list
print(a[:]) # Get all elements in the list
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Example : Get all items before/after a specific position


a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements starting from index 2 to the end of the list
b = a[2:]
print(b)
# Get elements starting from index 0 to index 3 (excluding 3th index)
c = a[:3]
print(c)
Output
[3, 4, 5, 6, 7, 8, 9]
[1, 2, 3]

Example : Get all items between two positions


a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Get elements from index 1 to index 4 (excluding index 4)
b = a[1:4]
print(b)
Output
[2, 3, 4]

Example : 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]
# Get every second element from the list starting from the beginning
b = a[::2]
print(b)
# Get every third element from the list # starting from index 1 to 8(exclusive)
c = a[1:8:3]
print(c)

Output
[1, 3, 5, 7, 9]
[2, 5, 8]
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.

Example :

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

# Get elements starting from index -2 to end of list


b = a[-2:]
print(b)

# Get elements starting from index 0 to index -3(excluding 3th last index)
c = a[:-3]
print(c)

# Get elements from index -4 to -1 (excluding index -1)


d = a[-4:-1]
print(d)

# Get every 2nd elements from index -8 to -1(excluding index -1)


e = a[-8:-1:2]
print(e)

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

Example : Reverse a list using slicing

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

b = a[::-1] # Get the entire list using negative step


print(b)

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

List Comprehension in Python


List comprehension is a way to create lists using a concise syntax. It allows us to
generate a new list by applying an expression to each item in an
existing iterable (such as a list or range).

Syntax of list comprehension

[expression for item in iterable if condition]


 expression: The transformation or value to be included in the new list.
 item: The current element taken from the iterable.
 iterable: A sequence or collection (e.g., list, tuple, set).
 if condition (optional): A filtering condition that decides whether the
current item should be included.
This syntax allows us to combine iteration, modification, and conditional
filtering all in one line.
For example, if we have a list of integers and want to create a new list containing
the square of each element, we can easily achieve this using list comprehension.

a = [2,3,4,5]
res = [val ** 2 for val in a]
print(res)

Output
[4, 9, 16, 25]

a = [1, 2, 3, 4, 5]
res = [val for val in a if val % 2 == 0]
print(res)
Output
[2, 4]

Python List Comprehension with Slicing


The syntax for using list comprehension with slicing is:

[expression for item in list[start : stop : step] if condition]


Parameters:
 expression: The operation or transformation to apply to elements.
 item: The current element from the sliced portion of the list.
 list[start:stop:step]: The sliced part of the list.
 condition (optional): A filter to include specific elements

Example
a = [1, 2, 3, 4, 5]
# Create a new list where each element in the
# first 3 elements of 'a' is multiplied by 2
result = [x * 2 for x in a[:3]]
print(result)

Output
[2, 4, 6]
Explanation:
 slicing nums[:3] selects the first three elements of the list [1, 2, 3].
 expression x * 2 doubles each element in the sliced list.
 result is a new list containing the doubled values [2, 4, 6].
Example
Filtering Even Numbers from a Slice
a = [1, 2, 3, 4, 5, 6]

# Filter even numbers from the last three elements


evens = [x for x in a[-3:] if x % 2 == 0]
print(evens)

Output
[4, 6]
Explanation:
 The slicing nums[-3:] selects the last three elements of the list [4, 5, 6].
 The condition if x % 2 == 0 filters out numbers that are not even.

Using Step in Slicing


Using a step value in slicing allows us to skip elements at defined intervals.
Combining this with list comprehension helps create patterned subsets, or
simplifying repetitive patterns in a list.

# Extract squares of alternate elements


a = [1, 2, 3, 4, 5]
squared = [x**2 for x in a[::2]]
print(squared)
Output
[1, 9, 25]
Explanation:
 The slicing nums[::2] selects every alternate element, starting from the
first ([1, 3, 5]).
 The expression x**2 squares each element in the selected sublist.

List parameter
Passing a List as an Argument

We can pass any data types of argument or parameter as an actual argument to a


function (string, number, list, dictionary etc.), and the receiving formal parameter
must be the same data type inside the function.

Example if we pass a List as an actual argument, then the receiving formal


parameter must be list:

def name(sname):
for x in sname:
print(x)
return
fname = ["Vijay", "Yash", "Vinay"]
name(fname)
Output
Vijay
Yash
Vinay

Python Program to Swap Two Elements in a List

a = [10, 20, 30, 40, 50]

# Swapping elements at index 0 and 4 # using multiple assignment


a[0], a[4] = a[4], a[0]

print(a)
Output
[50, 20, 30, 40, 10]

Python program to interchange first and last elements in a list

a = [10, 20, 30, 40, 50, 60, 70, 90, 100, 110, 120]

a[0], a[-1] = a[-1], a[0]

print(a)

Output
a = [120, 20, 30, 40, 50, 60, 70, 90, 100, 110, 10

Aliasing
Aliasing is when two or more variables refer to the same object.
Aliasing involves multiple variables pointing to the same object, while cloning
creates a new copy of the object.

Example
def message(name):
print(f"Hello {name}, welcome to Home!!!")

text = message
print(f'The id of message() : {id(message)}')
print(f'The id of text() : {id(text)}')

message('Vijay')
text('Isha')

Output
The id of message() : 140525701967312
The id of text() : 140525701967312
Hello Vijay, welcome to Home!!!
Hello Isha, welcome to Home!!!
Example Example
l=[2,3,4] l=[2,3,4]
print(l) print(l)
k=l k=m=l
print(k)
print(id(l)) print(m)
print(id(k)) print(k)
print(id(l))
print(id(m))
Output print(id(k))
[2, 3, 4]
[2, 3, 4]
140525697869888
140525697869888 Output
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
140525697815488
140525697815488
140525697815488
Cloning/copying
Cloning in Python involves creating a duplicate copy of an existing object.
The cloned object is a new independent entity, separate from the original object.

Example

l=[2,3,4]
print(l)
k=l.copy()
print(k)
print(id(l))
print(id(k))

Output
[2, 3, 4]
[2, 3, 4]
140525714972928
140525714975424

1) Aliasing:
 Aliasing is when two or more variables refer to the same object.

 Aliasing involves multiple variables pointing to the same object, while


cloning creates a new copy of the object.

 Aliasing in Python refers to having multiple variables pointing to the same


object in memory.
When a variable is assigned the value of another variable, changes made to
one variable also affect the other variable.

 Aliasing can happen when multiple variables are assigned to the same object
without explicitly creating a separate copy.

2) Cloning:

 Cloning in Python involves creating a duplicate copy of an existing object.

 The cloned object is a new independent entity, separate from the original
object.

 Cloning can be achieved using various techniques such as slicing, the copy()
method, the deepcopy() function from the copy module, etc.

Differences between Aliasing and Cloning

 Aliasing involves multiple variables pointing to the same object, while


cloning creates a new copy of the object.
 Changes made to one variable in the case of aliasing will be reflected in other
variables, whereas changes made to a cloned object do not affect the original
object.
 Aliasing can lead to unintended side effects if not handled properly, while
cloning provides a safe way to work with separate copies of objects.
 Aliasing is more memory efficient as it doesn't create new copies of objects,
whereas cloning consumes additional memory to store duplicate objects.

Tuples
Python Tuple is a collection of objects separated by commas.
A tuple is similar to a Python list in terms of indexing, nested objects, and repetition
but the main difference between both is python tuple is immutable, unlike the
Python list which is mutable.
A tuple in Python is an ordered, immutable collection of items. Tuples are similar
to lists, but they cannot be changed after their creation. This makes them useful
for storing data that should not be modified, such as database records or
configuration settings.
What is Immutable in Tuples?

Unlike Python lists, tuples are immutable. Some Characteristics of Tuples in


Python.
 Like Lists, tuples are ordered and we can access their elements using their
index values
 We cannot update items to a tuple once it is created.
 Tuples cannot be appended or extended.
 We cannot remove items from a tuple once it is created.
Example

t = (1, 2, 3, 4, 5)
print(t[1])
print(t[4])
x=t[1]+t[2]
print(x)

t = (1, 2, 3, 4, 2, 3) #tuples contain duplicate elements


print(t)

t[1] = 100 # updating an element


print(t)

Output:
2
5
5
(1, 2, 3, 4, 2, 3)
Traceback (most recent call last):
File "Solution.py", line 12, in <module>
t[1] = 100
TypeError: 'tuple' object does not support item assignment

Accessing Values in Python Tuples


Tuples in Python provide two ways by which we can access the elements of a
tuple.
1. Tuple using a Positive Index
Using square brackets we can get the values from tuples in Python.
Example
t = (10, 5, 20)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])
Output
Value in t[0] = 10
Value in t[1] = 5
Value in t[2] = 20

2. Tuple using Negative Index


In the above methods, we use the positive index to access the value in Python,
and here we will use the negative index within [ ].
Example
t = (10, 5, 20)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])

Output
Value in t[-1] = 20
Value in t[-2] = 5
Value in t[-3] = 10

Tuples Operations
Different Operations Related to Tuples

Concatenation of Python Tuples

To Concatenation of Python Tuples, the plus operators(+) is used

t1 = (0, 1, 2, 3)
t2 = ('python', 'Program')
print(t1 + t2) # Concatenating tuple t1 & t2

Output
(0, 1, 2, 3, 'python', 'Program')
Nesting of Python Tuples
A nested tuple in Python means a tuple inside another tuple.

t1 = (0, 1, 2, 3)
t2 = ('python', 'Program')
t3 = (t1, t2)
print(t3)

Output
((0, 1, 2, 3), ('python', 'Program'))

Example
t1 = (0, 1, 2, 3)
t2 = ('python', 'Program')
t3 = (t1,t2)
t4=t1+t2+t3
print(t3)
print(t4)

Output
((0, 1, 2, 3), ('python', 'Program'))
(0, 1, 2, 3, 'python', 'Program', (0, 1, 2, 3), ('python','Program'))

Repetition Python Tuples

We can create a tuple of multiple same elements from a single element in that
tuple.

t = ('python',)*3 t = ('python',)
print(t) print(t*3)

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

t = ('python’)*3 t = ('python')
print(t) print(t*3)

Output
pythonpythonpython

Slicing Tuples in Python


Slicing a Python tuple means dividing a tuple into small tuples using the
indexing method.

t = (0 ,1, 2, 3)
print(t[:])
print(t[1:])
print(t[:3:2])
print(t[:3:2])
print(t[::-1])
print(t[2:4])

Output
(0, 1, 2, 3)
(1, 2, 3)
(0, 2)
(0, 2)
(3, 2, 1, 0)
(2, 3)

Deleting a Tuple in Python


We can delete a tuple using ‘del’ keyword. The output will be in the form of error
because after deleting the tuple, it will give a NameError.

Note: Tuples are immutable, therefore removing individual tuple elements is not
possible, but we can delete the whole Tuple using Del keyword.

t = (0,1,5,7)
,del t
print(t)

Output:
Gives Error

Finding the Length of a Python Tuple

To find the length of a tuple, we can use Python’s len() function.


Tuples in Python are heterogeneous in nature. This means tuples support elements
with multiple datatypes.

t = ('python', 'for', 3, 4.5,True)


t1= (3, 4, “python”)
print(len(t))
print(len(t1))

Output
5
3

Tuples in a Loop

t = ('python',2,’program’,56.78)

for i in t :
print(i)

Output
python
2
program
56.78

Passing tuple as parameter


def name(sname):
for x in sname:
print(x)
return

fname = ("Vijay", "Yash", "Vinay")


name(fname)

Distinguish between Lists and Tuples? Give an example for their


usage.

Feature List Tuple

Mutability Mutable (changeable) Immutable (unchangeable)

Syntax Defined using square brackets [] Defined using


parentheses ()

Use Cases Storing collections of items that may Storing collections of items
need to be modified, such as a list of that should not be
tasks or a shopping cart modified, such as
coordinates or database
records

Methods Supports methods for adding, Supports limited methods,


removing, and modifying elements mainly for accessing
(e.g., append(), remove(), sort()) elements
(e.g., count(), index())

Performance Generally slower due to mutability Generally faster due to


immutability

Memory Consumes more memory Consumes less memory


Usage

Key Differences between List and Tuple


S.No List Tuple

Tuples are immutable(cannot be


1 Lists are mutable(can be modified).
modified).

Iteration over lists is time-


2 Iterations over tuple is faster
consuming.

Lists are better for performing


Tuples are more suitable for
3 operations, such as insertion and
accessing elements efficiently.
deletion.

4 Lists consume more memory. Tuples consumes less memory

Tuples have fewer built-in


5 Lists have several built-in methods.
methods.

Lists are more prone to unexpected Tuples, being immutable are less
6
changes and errors. error prone.

List Usage
# Storing a list of tasks
tasks = ["Write report", "Send email", "Prepare presentation"]
print(tasks)
# Modifying the list
tasks.append("Attend meeting")
print(tasks)
tasks.remove("Send email")
print(tasks)

Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs.
Values in a dictionary can be of any data type and can be duplicated, whereas keys
can’t be repeated and must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes
it easier to find values.
A dictionary in Python is a built-in data structure that stores data in key-value
pairs. dictionary is mutable, meaning it can be changed after creation, and starting
from Python 3.7, it is ordered, preserving the insertion order of items. Dictionaries
are written with curly braces {}, with keys and values separated by a colon :
The following example shows the creation of dictionary

d = {}
d = {1: 'Python', 2: 'For', 3: 'you'}
student = {'rollno':125, 'name':'Vijay', 'amount':2000.50}
print(d)
print(student)

Output
{1: 'Python', 2: 'For', 3: 'you'}
{'rollno': 125, 'name': 'Vijay', 'amount': 2000.5}

 Python dictionary are Ordered.


 Dictionary keys are case sensitive: the same name but different cases
of Key will be treated distinctly.
 Keys must be immutable: This means keys can be strings, numbers, or
tuples but not lists.
 Keys must be unique: Duplicate keys are not allowed and any duplicate
key will overwrite the previous value.
 Dictionary internally uses Hashing. Hence, operations like search, insert,
delete can be performed in Constant Time.

Accessing Dictionary Items


We can access a value from a dictionary by using the key within square brackets
or using get()method.
d = { "name": "Vijay", 1: "Python", 2:”program” }

print(d["name"]) # Access using key


print(d.get("name")) # Access using get()

Output
Vijay
Vijay

Dictionary Methods
Python dictionaries come with several built-in methods for manipulating data:
 keys(): Returns a view object that displays a list of all the keys in the dictionary.
 values(): Returns a view object that displays a list of all the values in the
dictionary.
 items(): Returns a view object that displays a list of a dictionary's key-value tuple
pairs.
 update(): Updates the dictionary with the elements from another dictionary or
iterable of key-value pairs.
 clear(): Removes all items from the dictionary.
 copy(): Returns a shallow copy of the dictionary.
 fromkeys(): Creates a new dictionary with keys from iterable and values set to
value.

Adding and Updating Dictionary Items


We can add new key-value pairs or update existing keys by using assignment.

d = {1: 'Python', 2: 'For', 3: 'program'}

# Adding a new key-value pair


d["age"] = 22

# Updating an existing value


d[1] = "Python dict"

print(d)

Output
{1: 'Python dict', 2: 'For', 3: 'program', 'age': 22}

Removing Dictionary Items


We can remove items from dictionary using the following methods:
 del: Removes an item by key.
 pop(): Removes an item by key and returns its value.
 clear(): Empties the dictionary.
 popitem(): Removes and returns the last key-value pair.

d = {1: 'Python', 2: 'For', 3: 'program', 'age':22}

del d["age"] # Using del to remove an item


print(d)

# Using pop() to remove an item and return the value


val = d.pop(1)
print(val)
print(d)
# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f" {key} : {val}")
print(d)

d.clear() # Clear all items from the dictionary

print(d)

Output
{1: 'Python', 2: 'For', 3: 'program'}
Python
{2: 'For', 3: 'program'}
3 : program
{2: 'For'}
{}

Iterating Through a Dictionary

We can iterate over


 keys [using keys() method]
 values [using values() method]
 or both [using items() method] with a for loop.

d = {1: 'Python', 2: 'For', 'age':22}

for k in d: # Iterate over keys


print(k)

for v in d.values(): # Iterate over values


print(v)

# Iterate over key-value pairs


for key, value in d.items():
print(f"{key}: {value}")

Output
1
2
age
Python
For
22
1: Python
2: For
age: 22

Difference between a List and a Dictionary


The following table shows some differences between a list and a dictionary in
Python:

List Dictionary

The list is a collection of index The dictionary is a hashed structure of the


value pairs like ArrayList in key and value pairs.
Java and Vectors in C++.

The list is created by placing The dictionary is created by placing


elements in [ ] separated by elements in { } as “key”:”value”, each key-
commas “, “ value pair is separated by commas “, “

The indices of the list are The keys of the dictionary can be of any
integers starting from 0. immutable data type.

The elements are accessed via


The elements are accessed via key.
indices.

They are unordered in python 3.6 and


The order of the elements
below and are ordered in python 3.7 and
entered is maintained.
above.

Dictionaries cannot contain duplicate keys


Lists can duplicate values since
but can contain duplicate values since each
each values have unique index.
value has unique key.

Average time taken to search a Average time taken to search a key in


value in list takes O[n]. dictionary takes O[1].

Average time to delete a certain Average time to delete a certain key from a
value from a list takes O[n]. dictionary takes O[1].

Describe the properties of list and dictionary.


Describe the properties of list in python
Lists in Python are versatile, ordered, mutable, and dynamic data structures used
to store collections of items. Their key properties include:
Ordered:
Lists maintain the order of elements as they are inserted, allowing access by
index.
Mutable:
Lists can be modified after creation; elements can be added, removed, or
changed.
Dynamic:
Lists can grow or shrink in size as needed, accommodating varying numbers of
elements.
Heterogeneous:
Lists can store elements of different data types (e.g., integers, strings, other lists)
within the same list.
Indexed:
Each element in a list has an index, starting from 0, enabling direct access to
specific items. Negative indices can also be used to access elements from the end
of the list.
Iterable:
Lists can be iterated over using loops, allowing for processing of each element.
Allows Duplicates:
Lists can contain duplicate values.
Nestable:
Lists can contain other lists, enabling the creation of multi-dimensional data
structures.

Common list operations include:


 Accessing elements: Using square brackets and the index (e.g., my_list[0]).
 Slicing: Extracting a portion of the list (e.g., my_list[1:4]).
 Adding elements: append() adds to the end, insert() adds at a specific position,
and extend() adds multiple elements from another iterable.
 Removing elements: remove() removes the first occurrence of a value,
and pop() removes an element at a specific index (or the last element if no index is
specified).
 Modifying elements: Assigning a new value to an element at a specific index
(e.g., my_list[2] = new_value).
 Searching: index() finds the index of the first occurrence of a value,
and count() counts the occurrences of a value.
 Sorting: sort() sorts the list in place.
 Reversing: reverse() reverses the order of elements in place.
 Copying: copy() creates a shallow copy of the list.
 List comprehension: Creating new lists based on existing iterables in a concise
way.
Describe the properties of dictionary.
dictionary, in programming, is a data structure that stores data as key-value
pairs. Keys must be unique and immutable, while values can be of any type,
including other dictionaries or lists. Dictionaries are mutable, meaning they can be
modified after creation, and in Python 3.7 and later, they are also ordered.

Here's a more detailed breakdown of dictionary properties:


Key-Value Pairs:
Dictionaries store data as pairs, where each key maps to a corresponding value.
Uniqueness of Keys:
Each key within a dictionary must be unique. Duplicate keys are not allowed, and
if a new value is assigned to an existing key, the old value is
overwritten, according to Tutorialspoint.
Immutability of Keys:
Keys must be immutable data types, meaning they cannot be changed after they
are created. Common immutable types include integers, strings, and tuples.
Any Value Type:
Values can be of any data type, including other dictionaries or lists, making them
versatile for storing complex data structures.
Mutability:
Dictionaries are mutable, meaning you can add, remove, or modify key-value
pairs after the dictionary is created.
Order (Python 3.7+):
In Python 3.7 and later, dictionaries are ordered, meaning the keys are stored in
the order they were inserted. In earlier versions, they were unordered.
Indexing and Slicing:
Indexing and slicing, common operations for lists and strings, are not applicable
to dictionaries.
Hashing:
Dictionaries use a hash function to determine the location of a key-value pair
within the dictionary, allowing for efficient lookups and insertion.

Write a program to create a list of five element and apply to


update and delete the list.

# Step 1: Create a list with 5 elements


my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print("Original list:", my_list)

# Step 2: Update an element (e.g., change 'banana' to 'blueberry')


my_list[1] = 'blueberry'
print("List after update:", my_list)

# Step 3: Delete an element (e.g., remove 'date')


del my_list[3]
print("List after deletion:", my_list)

Output:
Original list: ['apple', 'banana', 'cherry', 'date', 'elderberry']
List after update: ['apple', 'blueberry', 'cherry', 'date', 'elderberry']
List after deletion: ['apple', 'blueberry', 'cherry', 'elderberry']

Illustrate Union,Intersection and Difference operations to be


performed on sets along with an example.
sets can be manipulated using operations like union, intersection, and
difference. Union combines all elements from both sets, intersection finds
common elements, and difference returns elements unique to the first set.

# Define two sets


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

# Union
union_set = set1.union(set2) # or set1 | set2
print("Union:", union_set)

# Intersection
intersection_set = set1.intersection(set2) # or set1 & set2
print("Intersection:", intersection_set)

# Difference
difference_set = set1.difference(set2) # or set1 - set2
print("Difference (set1 - set2):", difference_set)

difference_set2 = set2.difference(set1) # or set2 - set1


print("Difference (set2 - set1):", difference_set2)

Output:

Union: {1, 2, 3, 4, 5, 6, 7}

Intersection: {3, 4, 5}

Difference (set1 - set2): {1, 2}


Difference (set2 - set1): {6, 7}

Explanation:
Union:
The union() method (or the | operator) combines all unique elements from both
sets. In this example, the union would be {1, 2, 3, 4, 5, 6, 7}.
Intersection:
The intersection() method (or the & operator) returns a new set containing only
the elements that are present in both input sets. Here, the intersection would
be {3, 4, 5}.
Difference:
The difference() method (or the - operator) returns a set containing elements that
are in the first set but not in the second set. In the first example, the
difference set1 - set2 would be {1, 2} (elements in set1 that are not in set2). The
second example, set2 - set1 would be {6, 7} (elements in set2 that are not
in set1).

You might also like