Unit v Data Structures Lists, Sets, Tuples, Dictionaries

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

Data Structures:

Lists, Sets, Tuples,


Dictionaries
Unit V
Lists-creating lists, list operations, list methods, mutability
list functions, searching and sorting, Sets-creating sets, set
operations. Tuples-Tuple assignment, Operations on
Tuples, lists and tuples, Tuple as return value- Dictionaries-
operations and methods, Nested Dictionaries.
Lists-creating lists
List
List is a sequence of values
The values in list can be of any type.
The values in list are called as elements or items
separated by commas and enclosed within square
brackets.
List with another list is called Nested List.
List contains no element are called Empty List
represented by [].
Example
A = [10, 20, 30, 40] #list of integers
B = [‘aaa’, ‘bbb’, ‘ccc’] #list of strings
C = [‘a’, 10, 20, ‘b’, 33.33] #mixed list
D = [10, 20, [‘a’, ‘b’, ‘c’]] #nested list
List operations
List Operations
List Operations namely:
1. Concatenation (+)
2. Repetition (*)
and many more..
1. Concatenation using +
Two list are created and can be joined using +
operator.
Example:
>>> L1=[10, 20, 30]
>>> L2=[40, 50, 60]
>>> L = L1+ L2
>>> print(L)
[10, 20, 30, 40, 50, 60]
2. Repetition using *
Operator * is used to repeat the list for number of
times
Example:
>>> L=[10, 20, 30]
>>> L*3
[10, 20, 30, 10, 20, 30, 10, 20, 30]
3. len([1,2,3]) - O/P: 3
4. "A" in ['a','e','i','o','u'] - O/P: False
5. "A" not in ['a','e','i','o','u'] - O/P: True
6. Num_list = [5,6,3,1,4,8,5]
print(max(Num_list))
O/P: 8
7. Num_list = [5,6,3,1,4,8,5]
print(min(Num_list))
O/P: 1
8. Num_list = [5,6,3,1,4,8,5]
print("Sum= “, sum(Num_list))
O/P: Sum= 32
9. new_list = "Hello"
Modified = list(new_list)
O/p: ['H','e','l','l','o’]
10. Num_list = [5,6,3,1,4,8,5]
modified = sorted(Num_list)
print(modified)
O/P: [1,3,4,5,5,6,8]
List methods
1. append()
Adds an values to the end of the list.
E.g.
num_list = [2,3,5,6,7]
num_list.append(11)
print(num_list)
O/P:
[2,3,5,6,7,11]
2. count()
Counts the number of times an values appears in a list.
E.g.
print(num_list.count(4))
O/P:
0
3. insert()
Insert the value at the specified location.
E.g
num_list.insert(2,15)
print(num_list)
O/P:
[2,3,15,5,6,7,11]
4. pop()
Removes the values at the specified index location. By default, last value is
deleted.
E.g
num_list.pop(2)
print(num_list)
num_list.pop()
print(num_list)
O/P:
[2,3,5,6,7,11]
[2,3,5,6,7]
5. remove()
Removes the values from the list. Error is generated
if the value is not found.
E.g
num_list.remove(5)
print(num_list)
O/P:
[2,3,6,7]
6. reverse()
Searching and
sorting
Linear Search
def search(arr, x):
flag=0
for i in range(len(arr)):
if arr[i] == x:
print(i)
flag+=1

if(flag==0):
print("Not found")

arr = [2,4,6,1,12,46,22,5]
x = 62
search(arr,x)
Sorting
arr = [3,5,12,34,78,23,87,23,0]
arr1 = ['aa','rr','gg','as']
print(sorted(arr))
print(sorted(arr1))
• Selection sort:
Selection Sort is one of the simplest sorting algorithms. It
selects the current smallest element, and swaps it into
place.
• Bubble Sort:
It works by repeatedly swapping the adjacent elements if
they are in the wrong order.
Tuples
Tuples
• Tuple items are ordered, unchangeable, and
allow duplicate values.
• Tuples are written with round brackets.
• E.g
thistuple = ("apple", "banana", "cherry")
print(thistuple)

O/P:
("apple", "banana", "cherry")
Create Tuple With One Item
• To create a tuple with only one item, you
have to add a comma after the item,
otherwise Python will not recognize it as a
tuple.
thistuple = ("apple",)
print(type(thistuple))

thistuple = ("apple")
print(type(thistuple))

O/P:
Operations on
Tuples
Operation Expression Output
Length len(8,3,6,2) 4
Concatenation (5,2,6) + (2,7,1) (5,2,6,2,7,1)
Repetition ("Hi ") * 3 "Hi Hi Hi"
Membership 9 in (5,2,6,2,7,1) False
Comparison tup1 = (4,6,1,2)
(use <, >, ==) tup2 = (4,6,1,2)
print(tup1<tup2) False
Maximum max(4,6,1,2) 6
Minimum min(4,6,1,2) 1
Tuple as return
value
Tuple as return value
• It is preferable to use tuple, in order to return multiple values
from a function.
• Program to return max and min value from a function.
def max_min(vals):
x = max(vals)
y = min(vals)
return (x, y)
vals = (34, 45, 99, 67, 12, 5, 24)
(max_val, min_val) = max_min(vals)
print("The maximum value is: ", max_val,\
", and the minimum value is: ", min_val)
Sets-creating sets
Sets
• A set is a collection which is unordered, unchangeable*,
and unindexed.
• Sets do not allow duplicate values.
• Once a set is created, you cannot change its items, but
you can remove items and add new items.
• The values True and 1 are considered the same value in
sets, and are treated as duplicates
• You cannot access items in a set by referring to an index
or a key.
thisset = {"apple", "banana", "cherry"}
print(thisset)
O/P:
Set operations
1. Add Items
• To add one item to a set use the add() method.
• E.g.
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

O/P
????
2. Add Sets
• To add items from another set into the current set, use the
update() method.
• update() method does not have to be a set, it can be any
iterable object
• E.g.

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)
O/P
????
3. Remove Item
• To remove an item in a set, use the remove(), or the
discard() method.
• E.g.

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)
O/P
????
Note: If the item to remove does not exist, remove() will
raise an error.
thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)
Note: If the item to remove does not exist, discard() will
NOT raise an error.
• pop() - Remove a random item
• clear() - Empties the set
• del - Delete the set completely
Method Description
difference() Returns a set containing the difference between
two or more sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)
print(z)
O/P:
{'banana', 'cherry'}
intersection() Returns a set, that is the intersection of two
other sets
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
O/P:
{'apple'}
Method Description
isdisjoint() Returns whether two sets have a intersection or
not
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "facebook"}
z = x.isdisjoint(y)
print(z)
O/P:
True
issubset() Returns whether another set contains this set or
not
x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
z = x.issubset(y)
print(z)
O/P:
True
Method Description
issuperset() Returns whether this set contains another set or
not
symmetric_differe Returns a set with the symmetric differences of
nce two sets
()
symmetric_differe inserts the symmetric differences from this set
nce_update() and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and
others
https://www.w3schools.com/python/
python_sets_methods.asp
Dictionaries-operations
and methods
Dictionaries
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do
not allow duplicates.
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year':
1964}
Accessing Items
• You can access the items of a dictionary by referring to its key
name, inside square brackets:
E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
print(x)
O/P:
Mustang
Get Keys
• The keys() method will return a list of all the keys in the dictionary.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict.keys()
print(x)
O/P:
dict_keys(['brand', 'model', 'year'])
Get Values
• The values() method will return a list of all the values in
the dictionary.
• E.g.
#refer previous example for variable declaration.
x = thisdict.values()

print(x)
O/P:
dict_values(['Ford', 'Mustang', 1964])
Get items
• The items() method will return each item in a dictionary,
as tuples in a list.
• E.g
x = thisdict.items()

print(x)
O/P:
dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year',
1964)])
Change Values
• change the value of a specific item by referring to its key
name
• E.g
thisdict["year"] = 2018

print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Adding Items
• Adding an item to the dictionary is done by using a new index key
and assigning a value to it:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
O/P:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
• The pop() method removes the item with the specified
key name:
• E.g
thisdict = { "brand": "Ford", "model": "Mustang",
"year": 1964 }
thisdict.pop("model")
print(thisdict)
O/P
{'brand': 'Ford', 'year': 1964}
• The del keyword removes the item with the specified key name:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
O/P
{'brand': 'Ford', 'year': 1964}
• The del keyword can also delete the dictionary completely:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict)
O/P:
Nameerror
Loop Through a Dictionary
• Print all key names in the dictionary, one by one:
• E.g
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
O/P
brand
Model
year
• Print all values in the dictionary, one by one:
E.G
for x in thisdict:
print(thisdict[x])
O/P
Ford
Mustang
1964
• Loop through both keys and values, by using the items()
method:
• E.g
for x, y in thisdict.items():
print(x, y)
O/P:
brand Ford
model Mustang
year 1964
Aliasing vs Copying
• Aliasing means creating a reference to the particular value with another
name.
E.G
>>> animals
['dog', 'cat', 'pig']
>>> animals_alias = animals #animals is aliased to animals_alias
>>> animals_alias
['dog', 'cat', 'pig’]
>>> animals.append("cow")
>>> animals
['dog', 'cat', 'pig', 'cow']
>>> animals_alias
['dog', 'cat', 'pig', 'cow']
• Copying means creating a exact duplicate copy of a
variable. It does not affect the values of a new variable.
E.G
a=["maths","phy","sci","pyt"]
b=a[:] #content of a is copied to b.
a.append("che")
print(a)
['maths', 'phy', 'sci', 'pyt', 'che']
print(b)
['maths', 'phy', 'sci', 'pyt']
Nested Dictionaries
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested
dictionaries.
• E.g
myfamily = { "child1" : { "name" : "Emil", "year" : 2004 },
"child2" : { "name" : "Tobias", "year" : 2007 },
"child3" : { "name" : "Linus", "year" : 2011 }
}

print(myfamily)
O/P
{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year':
2007}, 'child3': {'name': 'Linus', 'year': 2011}}
Access Items in Nested
Dictionaries
• To access items from a nested dictionary, you use the
name of the dictionaries, starting with the outer
dictionary:
• E.g
print(myfamily["child2"]["name"])
O/P:
Tobias

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy