Unit 3
Unit 3
Introduction:
A Data Structurer is a specialized format for organizing and storing data
Python has implicit support for Data Structures which enable you to store and access data.
Python has four basic inbuilt data structures namely Lists, Dictionary, Tuple and Set.
Lists:
1.1 Defining lists,accessing values in list
1.2 Deleting values in list, updating Basic List Operations
1.3 Built – in List functions
List
A List in python is linear data structure ie .Lists are used to store data of different data types in
a sequential manner. There are addresses assigned to every element of the list, which is called as
Index. The index value starts from 0 and goes on until the last element called the positive index.
There is also negative indexing which starts from -1 enabling you to access elements from the
last to first. Let us now understand lists better with the help of an example program.
Defining a List
In python list are written in square bracket .A List is created by placing all the items (elements
inside a square bracket [] , separated by commas.
Syntax for Defining a List
<list_name> =[val1,val2,………,valN] here list_name is the name of list and val1.val2,valN
are elements of list.
Unit 3: Data Structures in Python
Example
my_list =[1, 2, 3, 'example', 3.132]
List are mutable or changeable .the values of any element can be inside the list can be changed at
any point
Creating a List:
To create a list, you use the square brackets and add elements into it accordingly.
Example 1:
>>> l== [1, 2, 3, 'example', 3.132] #creating list with mixed data
>>> l=list(range(0,5))
>>l
[0,1,2,3,4]
‘six’
>>>list1[1:3] #get element from mth index to n-1 index
[‘two’,3]
>>>list1[3:] #get element from mth index to last index
[10,’six’,20]
>>>list1[:4] #get element from zero index to n-1
[‘one’,’two’,3,10]
● Use the del keyword which is built-in into Python but this does not return anything back
to us.del function can return one or more items from the list it can also delete list entirely.
● If you want the element back, you use the pop() function which takes the index value.
Pop method removes and returns the last item if index is not provided.
● To remove an element by its value, you use the remove() function.remove function is
used if we know the item that we want to remove or delete from the list (but not the
index)
Example:
Output:
[1, 2, 3, ‘example’, 3.132, 30]
[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]
● Using mutable data type program can be executed quickly and efficiently.
● List items can be updated by simply assigning the value at a particular index position .we
can also remove the item from the list using ‘remove’ or ‘pop’ or ‘del’ statement
Example 1:
Output
When the above code is executed, it produces the following result −
Example 2:
>>>list1=[10,20,30,40,50]
Unit 3: Data Structures in Python
>>>list1
[10,20,30,40,50]
>>>list1[0]=0 #change 0th index element
>>>list1
[0,20,30,40,50]
>>>list1[-1]=90 #change last index element
>>>list1
[0,20,30,40,90]
>>>list1[1]=[5,10] #change first element index as sublist
>>>list1
[[5,10],20,30,40,90]
Following table shows the list methods used for updating list
Method Syntax Argument description Return type
1.append()
The append() method appends an element to the end of the list. The length of the list increases
by one.
Unit 3: Data Structures in Python
Syntax
list.append(elmnt)
Parameter Values
Example
Add a list to a list:
output:
2.extend().
The extend() method adds the specified list elements (or any iterable) to the end of the current
list.
Syntax
list.extend(iterable)
Parameter Values
Example
output:
3.insert()
Unit 3: Data Structures in Python
The list insert() method inserts an element to the list at the specified index.
syntax
list.insert(i, elem)
Parameters
# vowel list
vowel = ['a', 'e', 'i', 'u']
# 'o' is inserted at index 3
# the position of 'o' will be 4th
vowel.insert(3, 'o')
Output
Output
Unit 3: Data Structures in Python
4. + operator
The most conventional method to perform the list concatenation, the use of “+” operator
can easily add the whole of one list behind the other list and hence perform the concatenation.
Example1:
list1 = [1, 4, 5, 6, 5]
list2= [3, 5, 7, 2, 5]
# using + operator to concat
list1 = list1 + list2
# Printing concatenated list
print("concatenated list"+str(list1))
Output:
concatenated list[1, 4, 5, 6, 5, 3, 5, 7, 2, 5]
5. * operator
The most conventional method to perform the list concatenation, the use of “+” operator can
easily add the whole of one list behind Using * operator
Using * operator, this method is the new addition to list concatenation and works only in Python
3.6+. Any no. of lists can be concatenated and returned in a new list using this operator.
Example1 :-
test_list1 = [1, 4, 5, 6, 5]
test_list2 = [3, 5, 7, 2, 5]
Example2:-
list = [1, 4, 5, 6, 5]
print(list *2)
Output:
[1, 4, 5, 6, 5, 1, 4, 5, 6, 5]
Indexing:
An individual item in the list can be referred by using an index, which is an integer number that
indicates the relative position of the item in the list.
1.Positive indexing
2. Negative Indexing
Now, let us look at the below diagram which illustrates a list along with its negative indexes.
Unit 3: Data Structures in Python
Example1:
>>>list=[‘p’,’y’,’t’,’h’,’o’,’n’]
>>>list[-1]
‘n’
>>>list[-6]
‘p’
>>>list[-3:]
[’h’,’o’,’n’]
>>>list[-7]
traceback (most recent call last):
File "main.py", line 2, in <module>
print(list[5])
IndexError: list index out of range
List Slicing
In Python, list slicing is a common practice and it is the most used technique for
programmers to solve efficient problems. Consider a python list, In-order to access a range of
elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator
i.e. colon(:)
With this operator, one can specify where to start the slicing, where to end, and specify the step.
List slicing returns a new list from the existing list.
Syntax:
If Lst is a list, then the above expression returns the portion of the list from index Initial to index
End, at a step size IndexJump.
[20,30,40,50]
>>>list[2:5]
[ 30,40,50]
Step is an integer value which determines the increment between each index for slicing
Syntax
List_name[start_index:end_index:step_size]
>>>a = [1, 2, 3, 4, 5, 6, 7, 8]
>>>print(a[:5]) # prints [1, 2, 3, 4, 5]
>>>print(a[2:]) # prints [3, 4, 5, 6, 7, 8]
>>>print(a[2:5]) # prints [3, 4, 5]
>>>print(a[2:7:2]) # prints [3, 5, 7]
Traversing a list
Means accessing all the elements or items in the list ,it can be performed by using any
conditional statement in python
Example
>>>a = [10, 20, 30]
for x in a
print(x)
Output
10
20
30
Output-
Extended List : [123, 'xyz', 'zara', 'abc', 123,
2009, 'manni']
Tuples
The list is better for performing operations, Tuple data type is appropriate for
3 such as insertion and deletion. accessing the elements
Creating Tuple
To create a tuple in Python, place all the elements in a () parenthesis, separated by
commas. A tuple can have heterogeneous data items, a tuple can have string and list as
data items as well.
<tuple_name>=(val1,val2,val3…….valn)
Here tuple name indicates name of yuples and val1,val2,val3……valn indicates values
assigned to tuple
Example1
Emp(20,”abc”,’m’,50)
Example2
# An empty tuple
empty_tuple = ()
print (empty_tuple)
Output:
()
Output
('python', 'tuple')
Output
('python', 'tuple')
Output:
Tuple assignment
Unit 3: Data Structures in Python
It allows a tuple of variables on the left of an assignment to be assigned values from a tuple on
the right of the assignment.
Example 1:
>>>Tup1=(11,”vaishali”,”Pune”)
>>>(id,name,city)=tup1
>>>Print(id)
11
>>>Print(name)
vaishali
Example2:
It is useful to swap the values of two variables. With conventional assignment statements, we
have to use a temporary variable. For example, to swap a and b:
Output:
(2, 3)
(3, 2)
Example 1:
Output
tup1[0]: physics
Unit 3: Data Structures in Python
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
Tuples are immutable which means you cannot update or change the values of
tuple elements. You are able to take portions of existing tuples to create new tuples
as the following example demonstrates −
output
To explicitly remove an entire tuple, just use the del statement. For example −
This produces the following result. Note an exception raised, this is because after deltup tuple
does not exist anymore −
Unit 3: Data Structures in Python
We can convert tuple into a list ,remove the item and convert back to a tuple
Tup1=(1,2,3,4,5)
List1=list(tup1)
Del list[2]0
B=typle(list)
Print(b)
Output
(1,2,4,5)
Tuple operations
There are three following sequence operations
The + operator creates a new tuple as the concatenation of the arguments. Here's an example.
>>>
("chapter",8) + ("strings","tuples","lists")
The * operator between tuples and numbers (number * tuple or tuple * number) creates a new tuple that is
a number of repetitions of the input tuple.
>>>
2*(3,"blind","mice")
2. Membership function
>>>t=(10,20,30,50)
>>> 30 in t
Unit 3: Data Structures in Python
True
>>>25 in t
False
1 len(tuple)
Gives the total length of the tuple. tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
Output−
Output −
Output −
Output −
Python has two built-in methods that you can use on tuples.
Set
Mathematically a set is a collection of items not in any particular order. A Python set is similar to
this mathematical definition with below additional conditions.
The elements in the set are immutable (cannot be modified) but the set as a whole is
mutable.
There is no index attached to any element in a python set. So they do not support any
indexing or slicing operation.
A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Sets are used to store multiple items in a single variable.
Unit 3: Data Structures in Python
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.
Python’s set class represents the mathematical notion of a set. The major advantage of using a
set, as opposed to a list, is that it has a highly optimized method for checking whether a specific
element is contained in the set. This is based on a data structure known as a hash table. Since sets
are unordered, we cannot access items using indexes like we do in lists
A set is a collection which is both unordered and unindexed.Setsare written with curly brackets.
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)
When the above code is executed, it produces the following result. Please note how the order of
the elements has changed in the result.
set(['Wed','Sun','Fri','Tue','Mon','Thu','Sat'])
set(['Jan','Mar','Feb'])
set([17,21,22])
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for dinDays:
print(d)
When the above code is executed, it produces the following result.
Wed
Sun
Fri
Tue
Unit 3: Data Structures in Python
Mon
Thu
Sat
Adding Items to a Set
We can add elements to a set by using add() method. Again as discussed there is no specific
index attached to the newly added element.
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
When the above code is executed, it produces the following result.
set(['Wed','Fri','Tue','Mon','Thu','Sat'])
6. Months.add ("August");
7. print("\nPrinting the modified set...");
8. print(Months)
9. print("\nlooping through the set elements ... ")
10. for i in Months:
11. print(i)
Output:
Set can be performed mathematical operation such as union, intersection, difference, and symmetric
difference. Python provides the facility to carry out these operations with operators or methods. We
describe these operations as follows.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
3. print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
The intersection_update() method is different from the intersection() method since it modifies the
original set by removing the unwanted items, on the other hand, the intersection() method returns a new
set.
{'castle'}
Unit 3: Data Structures in Python
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method
{'Thursday', 'Wednesday'}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
6. Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we
can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is
returned depending upon the items present inside the sets.
11. #prints false since Days2 and Days3 are not equivalent
12. print (Days2 == Days3)
Output:
True
False
False
SN Method Description
7 intersection_update(....) It removes the items from the original set that are
not present in both the sets (all the sets if more
than one are specified).
Dictionaries:
Accessing values in Dictionary, deleting
values in Dictionary and updating
Dictionary.
Basic Dictionary operations.
Built – in Dictionaries functions
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: {}.
Keys are unique within a dictionary while values may not be. The 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.
Unit 3: Data Structures in Python
dict={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Name']: ",dict['Name']
print"dict['Age']: ",dict['Age']
dict={'Name':'Zara','Age':7,'Class':'First'}
print"dict['Alice']: ",dict['Alice']
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']
Unit 3: Data Structures in Python
dict={'Name':'Zara','Age':7,'Class':'First'}
deldict['Name'];# remove entry with key 'Name'
dict.clear();# remove all entries in dict
deldict;# delete entire dictionary
print"dict['Age']: ",dict['Age']
print"dict['School']: ",dict['School']
This produces the following result. Note that an exception is raised because
after deldict 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
Note − del() method is discussed in subsequent section.
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object,
either standard objects or user-defined objects. However, same is not true for the
keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last assignment
wins. For example −
#!/usr/bin/python
dict={'Name':'Zara','Age':7,'Name':'Manni'}
Unit 3: Data Structures in Python
print"dict['Name']: ",dict['Name']
dict={['Name']:'Zara','Age':7}
print"dict['Name']: ",dict['Name']
{'Name':'Zara','Age':7};
Compares elements of dict2 ={'Name':'Mahnaz','Age':27};
both dict. dict3 ={'Name':'Abid','Age':27};
dict4 ={'Name':'Zara','Age':7};
print"Return Value : %d"%cmp(dict1, dict2)
print"Return Value : %d"%cmp(dict2, dict3)
print"Return Value : %d"%cmp(dict1, dict4)
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values set to value.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary dict, false otherwise
6 dict.items()
Returns a list of dict's (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict's keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary dict2's key-values pairs to dict
Unit 3: Data Structures in Python
10 dict.values()
Returns list of dictionary dict's values