unit3
unit3
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]
[]
Example 1:
Output
When the above code is executed, it produces the following result −
Example 2:
>>>list1=[10,20,30,40,50]
>>>list1
[10,20,30,40,50]
>>>list1[0]=0 #change 0th index element
>>>list1
[0,20,30,40,50]
Unit 3: Data Structures in Python
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.
Syntax
list.append(elmnt)
Parameter Values
Unit 3: Data Structures in Python
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()
The list insert() method inserts an element to the list at the specified index.
syntax
list.insert(i, elem)
Unit 3: Data Structures in Python
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
4. + operator
Unit 3: Data Structures in Python
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:
Unit 3: Data Structures in Python
[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.
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.
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']
Unit 3: Data Structures in Python
Tuples
● A tuple is a liner data structurer.
● A python tuple is a sequence of data value called as items or elements
● A Tuple is a data structure that is an immutable or unchangeable ordered sequence e of
elements/items because tuples are immutable their values cannot be modified
● A tuple is a heterogeneous data structure and used for grouping data. Each element or value
that is inside a tuple is called an item
● In python tuple is written in round bracket value of tuple can be assessed from its index,
which are integer start from 0.
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.
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
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
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 −
deltup;
print "After deleting tup : ";
printtup;
This produces the following result. Note an exception raised, this is because after deltup tuple does
not exist anymore −
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
Unit 3: Data Structures in Python
>>>t=(10,20,30,50)
>>> 30 in t
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
Unit 3: Data Structures in Python
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.
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])
Unit 3: Data Structures in Python
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
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"])
Unit 3: Data Structures in Python
Days.discard("Sun")
print(Days)
When the above code is executed, it produces the following result.
set(['Wed','Fri','Tue','Mon','Thu','Sat'])
To add more than one item in the set, Python provides the update() method. It accepts iterable as an
argument.
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:
Unit 3: Data Structures in Python
{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'}
{'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
Unit 3: Data Structures in Python
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.
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.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −
#!/usr/bin/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']
dict={'Name':'Zara','Age':7,'Class':'First'}
Unit 3: Data Structures in Python
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'}
print"dict['Name']: ",dict['Name']
dict={['Name']:'Zara','Age':7}
print"dict['Name']: ",dict['Name']
2 len(dict) Gives the total length of the dictionary. This would be equal
to the number of items in the dictionary.
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
10 dict.values()
Returns list of dictionary dict's values