0% found this document useful (0 votes)
6 views17 pages

Data Structures - 3rd Unit

The document provides an overview of basic list operations, methods, and access techniques in Python, including concatenation, repetition, membership testing, and slicing. It also covers tuple creation, access, and operations, emphasizing their immutability, as well as set creation and operations such as union and intersection. This information is essential for understanding data structures in Python programming.

Uploaded by

niharikap229
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)
6 views17 pages

Data Structures - 3rd Unit

The document provides an overview of basic list operations, methods, and access techniques in Python, including concatenation, repetition, membership testing, and slicing. It also covers tuple creation, access, and operations, emphasizing their immutability, as well as set creation and operations such as union and intersection. This information is essential for understanding data structures in Python programming.

Uploaded by

niharikap229
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/ 17

Data Structures -3rd unit

Lists:
Basic List Operations:
List Operations refer to actions that can be performed on lists, such as
concatenation ( + ), repetition ( * ), membership testing ( in ), and slicing ( [:] ).
These operations allow you to manipulate lists in various ways without
modifying the original list.

Concatenation: list1 + list2 joins two lists together.

my_list = [1, 2, 3]
concatenated_list = my_list + [4, 5, 6]
print("Concatenated list:", concatenated_list)

Output:
Concatenated list: [1, 2, 3, 4, 5, 6]

Repetition: list1 * 3 repeats the elements of list1 three times.

my_list = [1,2,3]
repeated_list = my_list * 2
print("Repeated list:", repeated_list)

Repeated list: [1, 2, 3, 1, 2, 3]

Membership testing: element in list1 checks if element is present in list1 .

my_list = [1,2,3]
is_present = 2 in my_list
print("Is 2 present in the list?", is_present)

Is 2 present in the list? True

Data Structures -3rd unit 1


Slicing: list1[1:3] returns a sublist containing elements at index 1 and 2 of
list1 .

my_list = [1,2,3]
sublist = my_list[1:3]
print("Sublist:", sublist)

Sublist: [2, 3]

List Methods:
append() : Adds an element to the end of the list.

my_list = [1,2,3]
my_list.append(4)
print(my_list)

[1, 2, 3, 4]

extend() : Appends elements from another list to the end of the list.

my_list.extend([5, 6])
print(my_list)

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

insert() : Inserts an element at a specified index.

my_list.insert(2, 7)
print(my_list)

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

remove() : Removes the first occurrence of a specified value.

Data Structures -3rd unit 2


my_list.remove(3)
print(my_list)

[1, 2, 7, 4, 5, 6]

pop() : Removes and returns the element at a specified index (or the last
element if no index is specified).

popped_value = my_list.pop(0)
print( popped_value)

index() : Returns the index of the first occurrence of a specified value.

index_of_5 = my_list.index(5)
print(index_of_5)

count() : Returns the number of occurrences of a specified value.

count_of_4 = my_list.count(4)
print(count_of_4)

sort() : Sorts the list in ascending order.

my_list.sort()
print(my_list)

[2, 4, 5, 6, 7]

Data Structures -3rd unit 3


reverse() : Reverses the order of the list.

my_list.reverse()
print(my_list)

[7, 6, 5, 4, 2]

Accessing Lists:
indexing:

List items are indexed and you can access them by referring to the index
number:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

banana

Negative Indexing:

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

cherry

Range of Indexes:

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.

Data Structures -3rd unit 4


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "me
print(thislist[2:5])

['cherry', 'orange', 'kiwi']

By leaving out the start value, the range will start at the first item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "me


print(thislist[:4])

['apple', 'banana', 'cherry', 'orange']

By leaving out the end value, the range will go on to the end of the list:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "me


print(thislist[2:])

['cherry', 'orange', 'kiwi', 'melon', 'mango']

Range of Negative Indexes:

Specify negative indexes if you want to start the search from the end of the list:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "me


print(thislist[-4:-1])

['orange', 'kiwi', 'melon']

Updating Lists:
To update elements in a list in Python, you can simply assign a new value to the
desired index. Here's how you can update elements in a list:

1. Updating a Single Element:

Data Structures -3rd unit 5


my_list = [1, 2, 3, 4, 5]
my_list[2] = 10
print(my_list)

Output: [1, 2, 10, 4, 5]

2. Updating Multiple Elements Using Slicing:

my_list = [1, 2, 3, 4, 5]
my_list[1:3] = [20, 30]
print(my_list)

Output: [1, 20, 30, 4, 5]

3. Updating the Last Element Using Negative Indexing:

my_list = [1, 2, 3, 4, 5]
my_list[-1] = 50
print(my_list)

Output: [1, 2, 3, 4, 50]

In each case, the specified elements in the list are updated with the new values,
modifying the original list.

Nested lists:
In Python, a nested list is a list that appears as an element in another list. This
means you have a list inside another list. Nested lists are useful for
representing matrix-like structures and other complex data types. Here's an
example of a nested list:

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

In this example, nested_list contains three inner lists, each representing a row
in a matrix. To access elements in a nested list, you use multiple levels of
indexing. The first index refers to the outer list (rows), and the second index
refers to the inner list (columns). Here's how you can access elements in the
nested list:

Data Structures -3rd unit 6


print(nested_list[0])

print(nested_list[1][1])

print(nested_list[2][2])

[1, 2, 3]
5
9

Loops in lists:
Loops are commonly used with lists in Python to iterate over the elements of
the list. There are two main types of loops that are used with lists:

1. For Loop: A for loop is used to iterate over a sequence of elements, such
as a list. Here's how you can use a for loop to iterate over a list:

my_list = [1, 2, 3, 4, 5]
for element in my_list:
print(element)

Output:

1
2
3
4
5

2. While Loop: A while loop is used to iterate over a list based on a condition.
Here's an example:

my_list = [1, 2, 3, 4, 5]
i = 0
while i < len(my_list):

Data Structures -3rd unit 7


print(my_list[i])
i += 1

Output:

1
2
3
4
5

In both examples, the loop iterates over each element in the list ( my_list ) and
prints it. You can perform any operations you need within the loop, such as
updating elements, appending elements to a new list, or performing
calculations.

Tuples:
Creation of tuples:
In Python, tuples are created by enclosing elements in parentheses () and
separating them with commas. Tuples are similar to lists, but they are
immutable, meaning their elements cannot be changed after creation. Here are
some examples of creating tuples:

1. Creating a Tuple with Single Element:


To create a tuple with a single element, you need to include a comma
, after the element, even though there is only one element.

single_element_tuple = (1,)

2. Creating a Tuple with Multiple Elements:

multiple_elements_tuple = (1, 2, 3, 4, 5)

3. Creating a Tuple without Parentheses:


Parentheses are optional for creating tuples. Python recognizes a comma-
separated sequence of values as a tuple.

Data Structures -3rd unit 8


tuple_without_parentheses = 1, 2, 3, 4, 5

Once created, tuples can be accessed using indexing and slicing, just like lists.
However, you cannot modify the elements of a tuple after it is created. Tuples
are often used to store related pieces of information that should not be
changed, such as coordinates, RGB values, or configuration settings.

Accessing Tuples:
Accessing elements in a tuple in Python is similar to accessing elements in a
list. You can use indexing and slicing to retrieve elements from a tuple. Here are
some examples:

1. Accessing Individual Elements:

my_tuple = (10, 20, 30, 40, 50)


first_element = my_tuple[0] # Accessing the first eleme
nt (10)
third_element = my_tuple[2] # Accessing the third eleme
nt (30)

2. Negative Indexing:
You can also use negative indexing to access elements from the end of the
tuple.

last_element = my_tuple[-1] # Accessing the last elemen


t (50)

3. Slicing:
Slicing allows you to access a subset of elements in the tuple.

subset = my_tuple[1:4] # Returns (20, 30, 40)

Updating Tuples:
Since tuples are immutable, you cannot directly update or modify their
elements. However, you can create a new tuple that incorporates the
changes you want. Here are some common techniques for "updating"
tuples:

Data Structures -3rd unit 9


1. Concatenating Tuples: You can concatenate two tuples to create a new
tuple that combines elements from both.

my_tuple = (1, 2, 3)
new_tuple = my_tuple + (4, 5, 6)

Output:

(1, 2, 3, 4, 5, 6)

2. Slicing and Concatenating: You can use slicing to modify parts of a


tuple and then concatenate them to create a new tuple.

my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:2] + (10, 20) + my_tuple[4:]

Output:

(1, 2, 10, 20, 5)

3. Converting to List: Convert the tuple to a list, modify the list, and then
convert it back to a tuple.

my_tuple = (1, 2, 3)
list_from_tuple = list(my_tuple)
list_from_tuple[1] = 10
new_tuple = tuple(list_from_tuple)

Output:

(1, 10, 3)

deletion in Tuples:
Since tuples are immutable in Python, you cannot delete elements from a
tuple. However, you can use other methods to achieve similar results, such
as creating a new tuple without the elements you want to "delete." Here are
some common approaches:

Data Structures -3rd unit 10


1. Creating a New Tuple: You can create a new tuple that excludes the
elements you want to "delete."

my_tuple = (1, 2, 3, 4, 5)
new_tuple = tuple(x for x in my_tuple if x != 3)

Output:

(1, 2, 4, 5)

2. Slicing: You can use slicing to create a new tuple that excludes the
elements you want to "delete."

my_tuple = (1, 2, 3, 4, 5)
new_tuple = my_tuple[:2] + my_tuple[3:]

Output:

(1, 2, 4, 5)

Basic tuple operations:


1. Creating a Tuple:

my_tuple = (1, 2, 3, 4, 5)

2. Accessing Elements:

first_element = my_tuple[0] # Accessing the first el


ement (1)

3. Slicing:

subset = my_tuple[1:3] # Returns (2, 3)

4. Concatenating Tuples:

Data Structures -3rd unit 11


combined_tuple = my_tuple + (6, 7, 8) # (1, 2, 3, 4,
5, 6, 7, 8)

5. Repeating Tuples:

repeated_tuple = my_tuple * 2 # (1, 2, 3, 4, 5, 1,


2, 3, 4, 5)

6. Tuple Length:

length = len(my_tuple) # 5

7. Tuple Membership:

is_present = 3 in my_tuple # True

8. Iterating Over a Tuple:

for element in my_tuple:


print(element)

Output:

1
2
3
4
5

These examples demonstrate basic tuple operations in Python. Tuples are


immutable, so their elements cannot be changed after creation.

Sets
Creation of Sets:
Sets in Python are created using curly braces {} .

1. Creating a Set with Elements:

Data Structures -3rd unit 12


my_set = {1, 2, 3, 4, 5}

2. Creating a Set from a List:

my_list = [1, 2, 3, 4, 5]
set_from_list = set(my_list)

When creating sets, it's important to note that sets do not allow duplicate
elements, and the elements are not ordered. If you need an ordered
collection with no duplicate elements, consider using a list and then
converting it to a set if necessary.

Set Operations:
Sets in Python support various operations for performing common set
operations like union, intersection, difference, and symmetric difference.
Here are the basic set operations with examples:

1. Union ( | or union() ): Combines two sets, returning a new set with all
unique elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2
# Or using union() method
# union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}

2. Intersection ( & or intersection() ): Returns a new set with elements that


are common to both sets.

intersection_set = set1 & set2


# Or using intersection() method
# intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}

3. Difference ( or difference() ): Returns a new set with elements that are


in the first set but not in the second set.

Data Structures -3rd unit 13


difference_set = set1 - set2
# Or using difference() method
# difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}

4. Symmetric Difference ( ^ or symmetric_difference() ): Returns a new set


with elements that are in either of the sets, but not common to both.

symmetric_difference_set = set1 ^ set2


# Or using symmetric_difference() method
# symmetric_difference_set = set1.symmetric_differenc
e(set2)
print(symmetric_difference_set) # Output: {1, 2, 4,
5}

5. Subset and Superset: You can also check if a set is a subset or


superset of another set.

subset = {1, 2}.issubset(set1) # True


superset = set1.issuperset({1, 2}) # True

These are some of the basic set operations in Python. Sets are mutable, so
these operations do not modify the original sets but return new sets with
the results.

Dictionaries:
Creation:

data = {
"name" : "Amarsiva",
"college" : "aditya",
"place" : "kkd",
"branch" : "AIR"
}
data

Data Structures -3rd unit 14


{'name': 'Amarsiva', 'college': 'aditya', 'place': 'kkd', '

Certainly! The data dictionary is created using curly braces {} and


contains key-value pairs separated by colons : . Each key is a string (e.g.,
"name" , "college" ) and is followed by a colon : , which is then followed by

the corresponding value (e.g., "Amarsiva" , "aditya" ).

Here's a breakdown of the dictionary data :

Key: "name" , Value: "Amarsiva"

Key: "college" , Value: "aditya"

Key: "place" , Value: "kkd"

Key: "branch" , Value: "AIR"

Accessing:
To access values from the data dictionary, you can use the keys. Here's
how you can access the values:

print(data["name"]) # Output: Amarsiva


print(data["college"]) # Output: aditya
print(data["place"]) # Output: kkd
print(data["branch"]) # Output: AIR

This code demonstrates how to access the values associated with each key
in the data dictionary.

Adding:
To update the data dictionary with the contents of the more_details
dictionary, you need to use the update method as follows:

more_details = {
"friends" : ["ravi","venky","mani"],
"fav movies" : ["saaho", "salaar", "kalki 2898AD"],
"ph no" : 9381360888,
"ipl_team" : "RCB"
}

Data Structures -3rd unit 15


data.update(more_details)

This will merge the more_details dictionary into the data dictionary, adding
the new key-value pairs. After this operation, the data dictionary will
contain all the key-value pairs from both dictionaries.
Here's the updated data dictionary after the update operation:

{
"name": "Amarsiva",
"college": "aditya",
"place": "kkd",
"branch": "AIR",
"year": "2025",
"friends": ["ravi","venky","mani"],
"fav movies": ["saaho", "salaar", "kalki 2898AD"],

"ph no": 9381360888,


"ipl_team": "RCB"
}

Modifying:
To modify a value in a dictionary, you can simply reassign a new value to
the key. Here's an example modifying the value associated with the key
"college" :

data["college"] = "new_college_name"

This will change the value associated with the key "college" to
"new_college_name" .
If you want to modify multiple values at once, you can use multiple
assignment or the update method:

data["college"], data["place"] = "new_college_name", "ne


w_place_name"

Data Structures -3rd unit 16


Both of these methods will update the values associated with the keys
"college" and "place" in the data dictionary.

Deleting:
To delete a key-value pair from a dictionary, you can use the del keyword
followed by the key you want to delete. For example, to delete the key "ph
no" and its associated value from your dictionary, you would do:

del data["ph no"]

After this operation, the data dictionary would look like this:

{
"name": "Amarsiva",
"college": "aditya",
"place": "kkd",
"branch": "AIR",
"year": "2025",
"friends": ["ravi","venky","mani"],
"fav movies": ["saaho", "salaar", "kalki 2898AD"],

"ipl_team": "RCB"
}

The key "ph no" and its associated value have been removed from the
dictionary.
Note : ##In exam when you are writing about accessing or adding or
modifying or deleting. first write about the creation part and then write
accesing or the topic which u got in dictionaries##

Data Structures -3rd unit 17

You might also like