Python-List, Tuple, Dictionary: Dr. Sarwan Singh NIELIT Chandigarh
Python-List, Tuple, Dictionary: Dr. Sarwan Singh NIELIT Chandigarh
@2022 sarwan@NIELIT 2
List
• Python has six built-in sequence types : strings, Unicode strings, lists,
tuples, buffers, and xrange objects. https://docs.python.org/2.4/lib/typesseq.html ) .
(source :
@2022 sarwan@NIELIT 3
List
• Each element of List is positioned/indexed starting from 0
• Operation on Strings like indexing, slicing, adding, multiplying, and
checking for membership are all available in Lists
• E.g. studentRec = [‘Amrit’, ‘kumar’ , 21, 2000 ]
recFields = [‘firstname’ , ‘lastname’, ‘rollno’, ‘fee’]
@2022 sarwan@NIELIT 4
Basic operations
• Basic operation on List are
similar to Strings
Expression Description
len Length
List1 + list2 Concatenation
List * 2 Repetition
‘elem’ in List Membership
for x in List: Iteration
@2022 sarwan@NIELIT 5
Built-in functions and Methods
• Min (list)
• Max (list)
• Len (list)
@2022 sarwan@NIELIT 6
Zip
• The purpose of zip() is to map the similar index of multiple containers so
that they can be used just using as single entity.
• passing two iterables, like lists, zip() enumerates them together
• Practical use:
student database or
scorecard or any
other utility that
requires mapping of
groups.
@2022 sarwan@NIELIT 7
LIST Equivalence/reference
• == equality operator
determines if two lists
contain the same elements
• is operator determines if
two variables alias the same
list
• The association of a variable
with an object is called a
reference
• Aliase : An object with more
than one reference has
more than one name
@2022 sarwan@NIELIT 8
Repetition adds one-level deep
• sequence repetition is like
adding a sequence to itself a
number of times
• When mutable sequences
are nested, effect is different
@2022 sarwan@NIELIT 9
FUNCTION DESCRIPTION
Append() Add an element to the end of the list
Extend() Add all elements of a list to the another list
Insert() Insert an item at the defined index
Remove() Removes an item from the list
Removes and returns an element at the
Pop()
given index
Clear() Removes all items from the list
Index() Returns the index of the first matched item
Source Geeksforgeeks.org
@2022 sarwan@NIELIT 12
• Tuples are immutable, cannot update or
change the values
• Tuples can be concatenated (+) , deleted
using del
• Other basic operation like list are same :
indexing, slicing, matrixes
@2022 sarwan@NIELIT 13
sequence packing-unpacking
• packing always creates tuple
• unpacking works for any sequence
• Parentheses is optional while packing
@2022 sarwan@NIELIT 14
Changing element of a tuple
• Immutable Types Can't Be
Changed in Place
@2022 sarwan@NIELIT 15
Tuple assignment
• swap a and b email = '[email protected]' un
Temp = a user, domain = email.split('@')
a= b
b = temp Comparing tuple
(0, 1, 2) < (0, 3, 4)
• tuple assignment is more elegant
True
a, b = b, a
a, b = 1, 2, 3 # error
ValueError: too many values to
unpack
@2022 sarwan@NIELIT 16
Python-Dictionary
Key : value pair separated with :
Uses curly brackets { }
Keys are unique in a dictionary, values may not
values of a dictionary can be of any type, but
the keys must be of an immutable data type
such as strings, numbers, or tuples
@2022 sarwan@NIELIT 17
Updation
• dict2['school']='DPS Delhi'
Deletion
• del dict1 ['name']; # remove entry with key 'Name'
• dict1.clear(); # remove all entries in dict1
• del dict1 ; # delete entire dictionary
@2022 sarwan@NIELIT 18
• Lists: used for collection of
Uses of Dictionary similar/non similar items.
• Tuples are generally used for
smaller groups of similar
• Web crawlers use dictionary for storing data items
• Store database settings
• Representing application templates
• In unit tests, sample data for web forms (mapping field name to
value)
• Mapping objects on game field – literally maps
• Building indexes of contents – phone book As today, more and more
web apps are moving to
• Exchanging data over Internet – JSON the RESTFul design
pattern, and JSON is key to
the client/server data
exchange.
@2022 sarwan@NIELIT 19
Methods
• Exercise :
• Write a python function to get all the
string elements inside tuple passed as
an argument (nested tuple)
• Without recursion
• With recursion
• Redefined method to accept list as an
argument
@2022 sarwan@NIELIT 20
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
Removes the arbitrary key-value pair from the dictionary and returns it
popitem()
as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp()
@2022 Compares elements of both dict.
sarwan@NIELIT 21
Jupyter Notebook Link
• https://colab.research.google.co
m/drive/1jUAhD0VvIz23RA8Hr25
pDzK__srpTcsm?usp=sharing
@2022 sarwan@NIELIT 22