3. LISTS
Python’s most flexible, ordered collection data type
Lists can contain any sort of object: numbers, strings, even
other lists
Python lists are:
Ordered collection of arbitrary objects
Accessed by offset
Variable length, heterogeneous, arbitrarily nestable
Of the category mutable sequence
3
5. UPDATING A LIST:
list = ['physics', 'chemistry', 1997, 2000]
print("Value available at index 2 :”)
print list[2]
list[2] = 2001
Print("New value available at index 2 :”)
print list[2]
Output:
Value available at index 2 :
1997
New value available at index 2 :
2001 5
6. DELETING A LIST:
list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print ("After deleting value at index 2 :”)
print list1
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000] 6
8. TUPLES
Tuples construct simple group of objects.
They are immutable
Usually written as a series of items in parenthesis.
Tuples are:
Ordered collection of arbitrary objects
Accessed by offset
Fixed length, heterogeneous, arbitrarily nestable
Of the category immutable sequence
8
9. CREATING A TUPLE:
Creating a tuple is as simple as putting different comma-
separated values. Or you can put these comma-separated
values between parentheses also.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
The empty tuple is written as two parentheses containing
nothing. For example − tup1 = ( )
To write a tuple containing a single value you have to
include a comma, even though there is only one value −
tup1 = (50,) 9
10. ACCESSING VALUES IN TUPLES:
To access values in tuple, use the square brackets
for slicing along with the index or indices to obtain
value available at that index.
For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
When the above code is executed, it produces the
following result −
tup1[0]: physics tup2[1:5]: [2, 3, 4, 5] 10
11. UPDATING TUPLES
Tuples are immutable which means you cannot
update or change the values of tuple elements. But,
you are able to take portions of existing tuples to
create new tuples as the following example
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100
# So let's create a new tuple as follows
tup3 = tup1 + tup2
print tup3
Output:
(12, 34.56, 'abc', 'xyz') 11
12. DELETING TUPLE ELEMENTS
Removing individual tuple elements is not possible. But, we can
delete the entire tuple using the del statement.
For example −
tup = ('physics', 'chemistry', 1997, 2000)
print(tup)
del tup
print (0)"After deleting tup : "
print (tup)
Output:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup
NameError: name 'tup' is not defined
12
14. DICTIONARIES
The dictionary contains Key-value pairs as its data
elements.
Each key is separated from its value by a colon (:),
the items are separated by commas, and the whole
thing is enclosed in curly braces.
An empty dictionary without any items is written
with just two curly braces, like this: { }.
Dictionaries are:
Unordered collection of arbitrary objects
Accessed by key, not offset
Variable length, heterogeneous, arbitrarily nestable
Of the category mutable mapping
14
15. ACCESSING VALUES IN DICTIONARY:
To access dictionary elements, you can use the
square brackets along with the key to obtain its value.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output:
dict['Name']: Zara
dict['Age']: 7
15
16. UPDATING DICTIONARY
You can update a dictionary by adding a new entry or a
key-value pair, modifying an existing entry, or deleting an
existing entry as shown below in the simple example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8
# update existing entry
dict['School'] = "DPS School"
# Add new entry
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
Output:
dict['Age']: 8 dict['School']: DPS School
16
17. DELETING DICTIONARY ELEMENTS
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement.
For example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name'] # remove entry with key 'Name'
dict.clear( ) # remove all entries in dict
del dict # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output:
Note that an exception is raised because after del dict dictionary does not exist
any more −
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age']
TypeError: 'type' object is unsubscriptable
17
19. SETS
Set is an unordered collection of collection of
unique and immutable objects that support
operations corresponding to mathematical set
theory.
By definition, an items appears only once in a set,
no matter how many times it is added
Sets are:
Unordered collection of arbitrary objects
Of the category immutable objects
19
20. CREATING A SET
A set is created by using the set( ) function or placing
all the elements within a pair of curly braces.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Output:
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
set(['Jan', 'Mar', 'Feb']) set([17, 21, 22])
20
21. ACCESSING VALUES IN A SET
We cannot access individual values in a set. We can only
access all the elements together as shown above. But we
can also get a list of individual elements by looping through
the set.
For Example –
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days: print(d)
Output:
Wed Sun Fri Tue Mon Thu Sat
21
22. ADDING ITEMS TO A SET
We can add elements to a set by using add() method.
There is no specific index attached to the newly
added element.
For example-
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
Output:
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 22
23. REMOVING ITEM FROM A SET
We can remove elements from a set by using
discard() method. There is no specific index attached
to the newly added element.
For example –
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
Output:
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat'])
23
24. UNION OF SETS
The union operation on two sets produces a new
set containing all the distinct elements from both
the sets.
In the below example the element “Wed” is present
in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays
= DaysA|DaysB
print(AllDays)
Output:
set(['Wed', 'Fri', 'Tue', 'Mon', 'Thu', 'Sat']) 24
25. INTERSECTION OF SET
The intersection operation on two sets produces a
new set containing only the common elements from
both the sets.
In the below example the element “Wed” is present
in both the sets.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
Output:
set(['Wed']) 25
26. DIFFERENCE OF SETS:
The difference operation on two sets produces a
new set containing only the elements from the first
set and none from the second set.
In the below example the element “Wed” is present
in both the sets so it will not be found in the result
set.
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB print(AllDays)
Output:
set(['Mon', 'Tue']) 26
27. COMPARE SETS
We can check if a given set is a subset or superset of another
set. The result is True or False depending on the elements
present in the sets.
For Example –
DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]) SubsetRes
= DaysA <= DaysB
SupersetRes = DaysB >= DaysA
print(SubsetRes)
print(SupersetRes)
Output:
True True 27
28. BUILT-IN SET METHODS AND OPERATIONS
add( )
remove( )
union
intersection
difference
symmetric difference
size
28