0% found this document useful (0 votes)
16 views

Unit 3

This document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It covers their creation, accessing elements, updating, deleting, and various methods associated with each structure. Additionally, it highlights key differences between these data structures, such as mutability and indexing capabilities.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit 3

This document provides an overview of data structures in Python, focusing on lists, tuples, sets, and dictionaries. It covers their creation, accessing elements, updating, deleting, and various methods associated with each structure. Additionally, it highlights key differences between these data structures, such as mutability and indexing capabilities.

Uploaded by

Siddhesh Rasane
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Unit 3

Data Structures in Python


14 marks
Lists
• Lists in Python is similar to arrays in C or Java.
• A list represents group of elements, of same or different data types
• The elements in a list can be accessed by their positions i.e. indices.
For a list with n elements the index starts with 0 to n-1
• The main difference between a list and an array is that a list can store
different type of elements but array can store only one type of
elements.
• Also list can grow dynamically in memory but the size of array is fixed
and can not grow runtime. Also values can be changed. This makes
the list mutable
• Lists are represented using [] and elements are written in [] separated
by ,
• For example: list=[10,-20,15.5,'Vijay']
Creating lists

• Using values • Using list()

>>>l1 = [] >>>l5 = list()


>>>l6 = list([“abc”, “pqr”, “lmn”])
>>>l2 = [1,2,3,4] >>>l7 = list(l1)
>>>l8 = list(“ABC”)
>>>l3 = [1,100.5,”Ram”] >>>l9 = list(range(5))
>>>l10 = list(x) ,where x is an iterable (string,
>>>l4 = [10, 25.45, [1,2,3]] list, tuple, set, dictionary)

#sublist or nested lists


Accessing elements of lists
• Positive indexing
>>> list1[0] 0 1 2 3 4 5
• Negative indexing 1 1.2 “a” 0 20 87
>>> list1[-1] -6 -5 -4 -3 -2 -1
• Slicing
>>> list[2:4] , elements from index 2 to 3
>>>list[2:] , elements from index 2 to end
>>>list[:3] , elements from index 0 to 2
>>>list[-4:] , last four elements of list
Slicing
• Slicing allows to obtain a specific set of elements from the sequence.
• The slicing operator, colon(:) returns a subset of the sequence, called
slice by specifying two indices, start and end
>>>l1=[1,2,3,4,5]
>>>l1[2:4]
[3,4]
• List slicing with step size
>>>l1=[1,2,3,4,5,6,7,8]
>>>l1[0:6:2]
[1,3,5]
>>>l2=[1,2,3,4,5]
>>>l2[::-1]
[5,4,3,2,1]
>>>l2[-1:0:-1]
[5,4,3,2]
Updating lists
• Using indexing and slicing
>>> l1 = [1,2,3] >>>l1[x:y] = l2 # replace elements from index x
to y with elements of l2

>>>l1[0] = 11
>>> l1[x:x] = l2 # works like insert

>>>l1[0] = [11,22]
# sublist at 0th index
Updating lists…….
• Using methods • Using + and * operators
+ Concatenation/ Join operator
• l1.append(x) – used to add an - used to combine elements of two lists
item x in list l1 >>>l1=[1,2,3]
• l1.extend(i) – used to add >>>l2=[‘A’,’B’,’C’]
iterable i at end of list l1 >>>l3=l1+l2
>>>l3
• l1.insert(i,x) – inserts item x at
[1,2,3,’A’,’B’,’C’]
index i in l1
• Multiplication operator
- used to repeat the elements of a list
>>>l1 = [‘A’,’B’]
>>>l2=l1*2
>>>l2
[‘A’,’B’,’A’,’B’]
Deleting elements of list
• Using value • Using index
• l1.remove(x) – removes element x from • l1.pop(x) – returns and removes
list element at index x
• del l1[x] - removes element x from list

• l1.clear() – removes all elements from list • del l1 – deletes the list l1
• l1.pop() – returns and removes last
element of list
• Check if item exists
>>>mylist = [ “apple”, “orange”, “cherry”, “banana”]
>>>if “apple” in mylist:
print(“Yes”)
Yes

• Iterate through list


>>>for x in [10,20]: >>>mylist=[[1,2],[‘a’, ‘b’, ‘c’], [10.2,3.5,89]]
print(x) >>>for i in mylist:
10 for j in i:
20 print(j, end=‘ ‘)
print(‘\n’)
>>>for i in range(len(mylist)):
print(i, mylist[i])
List Comprehension
• Returns a new list based on the values of an existing iterable.

>>>numbers = [1,2,3,4,5,6,7,8,9,10]
>>>days = [“sun”,”mon”,”tue”,”wed”]

>>>newlist = [ x**2 for x in numbers]


>>>workdays=[x.upper() for x in days]
>>>poll = [“yes” for x in days if x!=‘sun’]
>>>mydays =[x if x!=‘sun’ else ‘thu’ for x in days] # using short hand if-else
>>>mylist = [ x for x in range(10)]
>>>evenlist = [x for x in numbers if x%2==0]

>>>[n*2 for n in (2,4,6)]


>>>[x if x%2==0 else “Odd” for x in {24, 53, 45, 56, 88, 100}]
>>>[[p,q] for p in (10,100) for q in (‘a’, ‘b’)]
>>>[x for x in ‘jingalala’ if x not in ‘lol’]
Unpacking a list
• The elements of a list/tuple are allowed to be extracted into variables. This is
called unpacking

>>>mylist = [1,2,3,4,5]

>>>(a,b,c,d,e) = mylist >>>(a,*b,c) = mylist

>>>a >>>(*a,b,c) = mylist


1
>>>b >>>(a,b,*c) = mylist
2
>>>c
3
List methods and functions
• l1.sort() - sorts the list alphanumerically, ascending, by default. It is a case sensitive method.
• l1.sort(key=str.lower) – to perform case insensitive sort
• l1.sort(reverse = True) – sorts the list in descending order
• l1.reverse() – reverses the list elements
• l1.count(x) – returns count of element x in list l1
• l1.index(x) – returns index of first occurrence of element x in list l1
• l1.copy() – returns a copy of list l1

• len(l1) – function returns count of elements in list l1


• min(l1) – returns minimum of elements, provided they are of same type, either numeric or string
• max(l1) – returns maximum of elements, provided they are of same type, either numeric or string
• sum(l1) – returns sum of elements for numeric type elements
• sorted(l1) – returns sorted list in ascending order, provided they are of same type, either numeric or string
• sorted(l1, reverse=True) – returns list sorted in descending order, provided they are of same type, either numeric or string
Methods used with list class
Examples :
• Update
mylist=[1,2,3]:

list.append(mylist,10)
list.extend(mylist, x) #where, x is an iterable

……………..all methods can be used in similar manner


Tuples
• A tuple datatype is similar to list
• A tuple contains a group of elements which can be of different types
• The element in the tuple are separated by , and enclosed in
parenthesis ()
• Elements of a tuple cannot be modified
• Tuple is read only List
• For example:
tuple = [10, -20, 15.5, ‘PUNE']
Creating tuples
>>>t1 = (1,2,3,4)

>>>t2= (50,)

>>>t3 = (10, 67.8, ”abc”)

>>>t4 =(1, 2, 3, 23.8, ’a’, ‘abc’, [10,20,30], (11, 12), {1,2}) #nested tuple

>>>t5 = tuple(x) ,where x is an iterable (string, list, tuple, set, dictionary)

>>>t6 = tuple(range(5))
Accessing elements of tuple
• Positive indexing
• Negative indexing
• Slicing
Updating tuples
• Once created, elements cannot be added to or removed from the tuple

• If modification is needed it can be converted to list


>>>work_days=(“mon”, “tue”, “wed”)
>>>days = list(work_days)
>>>days.append(“thu”)
>>>days.remove(“mon”)
>>>new_work_days=tuple(days)

• If tuple contains mutable element, list then only the list elements can be updated,
>>>t1 = (1,2,3,[4,5])
>>>t1[3][0] = 14
>>>t1[3].remove(5)
>>>t1[3].append(100)
• Deletion • Looping
del t1 – deletes the tuple t1 >>>for x in (1,2,3):
>>>del t1 print(x**2)

• Unpacking >>>for i in range(len(t1))


>>>test = (“eng”, “phy”,”che”, “bio”) print(i, t1[i])
>>>(x,y,z) = test
• Check membership
• Concatenate and multiply >>>a in (‘a’, ‘b’, ‘c’)
>>>t3 = t1 + t2
>>>t4 = t1 * 3
Tuple methods and functions
• t1.count()
• t1.index()

• len(t1)
• max(t1)
• min(t1)
• sum(t1)
• sorted(t1) – returns a list with tuple elements in ascending order
Sets
• A set is an unordered collection of elements of same or different data
types much like a set in Mathematics
• The order of elements is not maintained in sets, it means the elements may
not appear in the same order as they entered into the set. Elements can be
numeric, string or tuple only.
• Lists and sets cannot be used as elements in sets, i.e. nested sets not allowed
• Since, sets are unordered, the elements cannot be retrieved using indexing or
slicing operations.
• It also does not allow duplicate elements.
• The elements of a set are separated by , and placed inside curly braces {}
• For example:
set1 = {10, -20, 15.5, ‘Pune’}
Creating sets
>>>s1 = {1,2,3,4}

>>>s2={10, 67.8, ”abc”}

>>>s3 = {“abc”}

>>>s4 = set()

>>>s5 = set(x) ,where x is an iterable (string,list, tuple, set, dictionary)

>>>s6 = set(range(5))

>>>s7 = {x for x in W} #Set comprehension, where W is an iterable (string, list, tuple, set, dictionary)
Accessing elements of sets
• Sets are unordered, no indexing. So individual values cannot be
accessed.

• Looping • Check membership


>>>s1={1,2,3} >>>a in {‘a’, ‘b’, ‘c’}
>>>for x in s1:
print(x)
Updating sets
• s1.add(x) – adds element x in set s1
• s1.update(i) – adds the elements of iterable i to set s1
• s1.remove(x) – removes element x from set s1
• s1.discard(x) – removes element x from set s1, does not raise error if x not in s1
• s1.pop() – returns an arbitrary element of s1
• s1.clear() – empties the set s1
• del s1 – deletes set s1
• s1.copy() – returns a copy of the set s1
Set Operations
Methods for set operations
s1.union(s2) returns a set of s1 union s2
s1 | s2
s1.intersection(s2) returns a set of s1 intersection s2
s1 & s2
s1.difference(s2) returns a set of s1 difference s2
s1 – s2
s1.symmetric_difference(s2) returns a set of s1 symmetric difference s2
s1 ^ s2

To update s1 to the result of set join operations then use,


• s1.update(s2)
• s1.intersection_update(s2)
• s1.difference_update(s2)
• s1.symmetric_difference_update(s2)
Functions
• len(s1)
• max(s1)
• min(s1)
• sum(s1)
• sorted(s1) – returns a list of set values sorted in ascending order

• s1.issubset(s2) – returns True if s1 is a subset of s2, else returns False


• s1.issuperset(s2) – returns True if s1 is a superset of s2 , else returns False
• s1.isdisjoint(s2) – returns True if there are no common elements in s1 and s2, else returns False
Dictionary (Mappingtype )
• A dictionary represents a group of elements in the form of key value pairs so
that if key is given, we can retrieve the value associated with it.
• Keys can be of int, float, Boolean, string or tuple data type
• Values can be of any data type
• The dict datatype represents dictionary. It is ordered and changeable.
Duplicate keys are not allowed. It means there cannot be two values with
same key
• The key and its value should be separated by : and every pair should be
separated by , and all the elements should be enclosed inside {}
• For example:
d = {10 : ’Pune’, 11 : ’Mumbai’, 12 : ’Nasik'}
Creating dictionary
>>>d1 = { }

>>>d2 = {1:1, 2:4, 3:9}

>>>d3 = { “abc” : 10, 25 : 100.25, (1,2) : “model”, “city”: {“Dhule”, “Pune”}}


#nested dictionary

>>>d4 = dict(x) #where x is a dictionary


Accessing dictionary items
>>>d={1:1, 2:4, 3:9}

>>>d[3]
>>>d.get(3) # does not raise error in case of wrong key

>>>d.keys() – returns a list of all keys


>>>d.values() – returns a list of all values
>>>d.items() – returns a list of tuples for each key value pair
Add and Update items in dictionary
>>>d={1:1, 2:4, 3:9}

>>>d[x] = y
- If key x is present in d then its value is replaced by y , else pair x:y is added to d

>>>d.update(d1)
- where, d1 is a dictionary and if d1 has same keys then pairs in d will be
replaced by those in d1
Accessing dictionary items
• Looping
>>>d = {1:1, 2:4, 3:9}
• To get the keys • To get the values
>>>for x in d.keys(): >>>for x in d.values():
print(x) print(x)

>>>for x in d: >>>for x in d:
print(x) print(d[x])

• To get the items • Check membership


>>>for (x, y) in d.items(): >>>1 in d
print(x, y) >>>5 not in d
Deleting items from dictionary
>>>d = {1:1, 2:4, 3:9}

>>>d.pop(x) – returns and removes item with key x


>>>d.popitem() – removes last item added

>>>d.clear() – empties the dictionary


>>>del d[x] – removes item with key x
>>>del d – deletes dictionary
Methods and Functions
• d.copy() – returns a copy of dictionary d
• dict.fromkeys(x,y) – returns a dictionary with keys as elements from iterable x (string,
list, tuple, set) and all values set to y (Optional, y is None by default)
• d.setdefault(x,y) – returns the value of key x, but if x is not present in d, then x is
inserted with value set to y (Optional, y is None by default)

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