unit 3
unit 3
Data Structures are a way of organizing data so that it can be accessed more efficiently
depending upon the situation. Data Structures are fundamentals of any programming
language around which a program is built. Python helps to learn the fundamental of these
data structures in a simpler way as compared to other programming languages.
we will discuss the Data Structures in the Python Programming Language and how they are
related to some specific Python Data Types. We will discuss all the in-built data
structures like list tuples, dictionaries, etc. as well as some advanced data structures like
trees, graphs, etc.
Python List
There are many built-in types in Python that allow us to group and store multiple items.
Python lists are the most versatile among them.
For example, we can use a Python list to store a playlist of songs so that we can easily add,
remove, and update songs as needed.
List Characteristics
Lists are:
We can change the items of a list by assigning new values using the = operator. For example,
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
# changing the third item to 'Blue'
colors[2] = 'Blue'
We can remove an item from a list using the remove() method. For example,
numbers = [2,4,7,9]
print(numbers)
# Output: [2, 7, 9]
Run Code
We can use the built-in len() function to find the number of elements in a list. For example,
cars = ['BMW', 'Mercedes', 'Tesla']
We can use a for loop to iterate over the elements of a list. For example,
fruits = ['apple', 'banana', 'orange']
apple
banana
orange
The extend() method adds all the items of the specified iterable, such as list, tuple, dictionary,
or string , to the end of a list.
Example
numbers1 = [3, 4, 5]
print(f"numbers1 = {numbers1}")
print(f"numbers2 = {numbers2}")
Run Code
Output
numbers1 = [3, 4, 5]
numbers2 = [10, 20, 3, 4, 5]
The insert() method inserts an element to the list at the specified index.
Example
print('List:', vowel)
Output: List: ['a', 'e', 'i', 'o', 'u']
list.insert(i, elem)
Here, elem is inserted to the list at the ith index. All the elements after elem are shifted to the
right.
list1.extend(iterable)
Output
list.clear()
clear() Parameters
The clear() method only empties the given list. It doesn't return any value.
print('List:', list)
Run Code
Output
List: []
# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]
Output
List: []
The count() method returns the number of times the specified element appears in the list.
Example
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
# Output: Count of 2: 3
Run Code
list.count(element)
count() Parameters
The count() method returns the number of times element appears in the list.
The reverse() method reverses the elements of the list.
Example
list.reverse()
reverse() parameter
The reverse() method doesn't return any value. It updates the existing list.
# List Reverse
systems.reverse()
# updated list
print('Updated List:', systems)
Run Code
Output
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
reversed_list = systems[::-1]
# updated list
print('Updated List:', reversed_list)
Run Code
Output
print(prime_numbers)
numbers.sort(reverse, key)
print(numbers)
Run Code
Output
[11, 7, 5, 3, 2]
Output
# mixed list
prime_numbers = [2, 3, 5]
# copying a list
numbers = prime_numbers.copy()
copy() Syntax
new_list = list.copy()
Python Tuple
A tuple is a collection similar to a Python list. The primary difference is that we cannot
modify a tuple once it is created.
print(numbers)
Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a
tuple.
print(cars)
Run Code
Output
apple
banana
orange
Delete Tuples
We cannot delete individual items of a tuple. However, we can delete the tuple itself using
the del statement. For example,
animals = ('dog', 'cat', 'rat')
print(count)
# Output: 2
The index() method returns the index of the specified element in the tuple.
Example
print(index)
# Output: 1
Python Dictionary
A Python dictionary is a collection of items, similar to lists and tuples. However, unlike lists
and tuples, each item in a dictionary is a key-value pair (consisting of a key and a value).
Create a Dictionary
We create a dictionary by placing key: value pairs inside curly brackets {}, separated by
commas. For example,
# creating a dictionary
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
The country_capitals dictionary has three elements (key-value pairs), where 'Germany' is the
key and 'Berlin' is the value assigned to it and so on.
Python Dictionary
Notes:
Dictionary keys must be immutable, such as tuples, strings, integers, etc. We cannot use
mutable (changeable) objects such as lists as keys.
We can also create a dictionary using a Python built-in function dict(). To learn more,
visit Python dict().
We can access the value of a dictionary item by placing the key inside square brackets.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
"England": "London"
}
We can add an item to a dictionary by assigning a value to a new key. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
print(country_capitals)
Output
We can use the del statement to remove an element from a dictionary. For example,
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
print(country_capitals)
Run Code
Output
{'Canada': 'Ottawa'}
Note: We can also use the pop() method to remove an item from a dictionary.
If we need to remove all items from a dictionary at once, we can use the clear() method.
country_capitals = {
"Germany": "Berlin",
"Canada": "Ottawa",
}
print(country_capitals)
Run Code
Output
{}
Python dictionaries are mutable (changeable). We can change the value of a dictionary
element by referring to its key. For example,
country_capitals = {
"Germany": "Berlin",
"Italy": "Naples",
"England": "London"
}
print(country_capitals)
Run Code
Output
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome"
}
print()
Output
United States
Italy
Washington D.C.
Rome
countries = {}
The pop() method removes and returns an element from a dictionary having the given key.
Example
# create a dictionary
marks = { 'Physics': 67, 'Chemistry': 72, 'Math': 89 }
element = marks.pop('Chemistry')
dictionary.pop(key[, default])
The keys() method extracts the keys of the dictionary and returns the list of keys as a view
object.
Example
print(dictionaryKeys)
keys() Syntax
dict.keys()
The values() method returns a view object that displays a list of all the values in
the dictionary.
Example
print(marks.values())
A set is a collection of unique data, meaning that elements within a set cannot be duplicated.
For instance, if we need to store information about student IDs, a set is suitable since student
IDs cannot have duplicates.
In Python, we create sets by placing all the elements inside curly braces {}, separated by
commas.
A set can have any number of items and they may be of different types (integer,
float, tuple, string, etc.). But a set cannot have mutable elements like lists, sets
or dictionaries as its elements.
Let's see an example,
Output
In the above example, we have created different types of sets by placing all the elements
inside the curly braces {}.
Note: When you run this code, you might get output in a different order. This is because the
set has no particular order.
Creating an empty set is a bit tricky. Empty curly braces {} will make an empty dictionary in
Python.
To make a set without any elements, we use the set() function without any argument. For
example,
# create an empty set
empty_set = set()
Output
Here,
Let's see what will happen if we try to include duplicate items in a set.
numbers = {2, 4, 6, 6, 2, 8}
print(numbers) # {8, 2, 4, 6}
Run Code
Here, we can see there are no duplicate items in the set as a set cannot contain duplicates.
Sets are mutable. However, since they are unordered, indexing has no meaning.
We cannot access or change an element of a set using indexing or slicing. The set data type
does not support it.
In Python, we use the add() method to add an item to a set. For example,
numbers = {21, 34, 54, 12}
print('Initial Set:',numbers)
Output
In the above example, we have created a set named numbers. Notice the line,
numbers.add(32)
The update() method is used to update the set with items other collection types (lists, tuples,
sets, etc). For example,
companies = {'Lacoste', 'Ralph Lauren'}
tech_companies = ['apple', 'google', 'apple']
print(companies)
Here, all the unique elements of tech_companies are added to the companies set.
We use the discard() method to remove the specified element from a set. For example,
languages = {'Swift', 'Java', 'Python'}
print('Initial Set:',languages)
Output
Here, we have used the discard() method to remove 'Java' from the languages set.
Here are some of the popular built-in functions that allow us to perform different operations
on a set.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
Returns an enumerate object. It contains the index and value for all the items of the se
enumerate()
pair.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
Output
Mango
Peach
Apple
Here, we have used for loop to iterate over a set in Python.
We can use the len() method to find the number of elements present in a Set. For example,
even_numbers = {2,4,6,8}
print('Set:',even_numbers)
Output
Set: {8, 2, 4, 6}
Total Elements: 4
Here, we have used the len() method to find the number of elements present in a Set.
Python Set provides different built-in methods to perform mathematical set operations like
union, intersection, subtraction, and symmetric difference.
The union of two sets A and B includes all the elements of sets A and B.
We use the | operator or the union() method to perform the set union operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {0, 2, 4}
Output
Set Intersection
The intersection of two sets A and B include the common elements between set A and B.
In Python, we use the & operator or the intersection() method to perform the set intersection
operation. For example,
# first set
A = {1, 3, 5}
# second set
B = {1, 2, 3}
Output
The difference between two sets A and B include elements of set A that are not present on
set B.
We use the - operator or the difference() method to perform the difference between two sets.
For example,
# first set
A = {2, 3, 5}
# second set
B = {1, 2, 6}
Output
The symmetric difference between two sets A and B includes all elements
of A and B without the common elements.
Set Symmetric Difference in Python
# second set
B = {1, 2, 6}
# using symmetric_difference()
print('using symmetric_difference():', A.symmetric_difference(B))
Run Code
Output
using ^: {1, 3, 5, 6}
using symmetric_difference(): {1, 3, 5, 6}
We can use the == operator to check whether two sets are equal or not. For example,
# first set
A = {1, 3, 5}
# second set
B = {3, 5, 1}
In the above example, A and B have the same elements, so the condition
if A == B
evaluates to True. Hence, the statement print('Set A and Set B are equal') inside the if is
executed.
There are many set methods, some of which we have already used above. Here is a list of all
the methods that are available with the set objects:
Method Description
intersection_update() Updates the set with the intersection of itself and another
symmetric_difference_update() Updates a set with the symmetric difference of itself and another
update() Updates the set with the union of itself and others