You are on page 1of 21

Python Programming Unit-3 Notes

CHAPTER 3- Data Structures in Python

Iterators
An iterator is an object that contains a countable number of values. It is an object that can be
iterated upon, meaning that you can traverse through all the values.

# Python program to illustrate iterating over a list

print("List Iteration")
l = ["ABC", "BCD", "CDE"]
for i in l:
print(i)

List Iteration
ABC
BCD
CDE

# Iterating over a tuple (immutable)

print("\Tuple Iteration")
t = ("ABC", "BCD", "CDE")
for i in t:
print(i)

Tuple Iteration
ABC
BCD
CDE

# Iterating over a String

print("String Iteration")
s = "ABCDE"
for i in s :
print(i)

String Iteration
A
B
C
D
E
Python Programming Unit-3 Notes

Python has four basic inbuilt data structures namely Lists, Tuple, Dictionary and Set.
List
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be
any type. The values in list are called elements or sometimes items.
There are several ways to create a new list; the simplest is to enclose the elements in square brackets
(“[” and “]”)

# Creating a List

List = [ ]
print("Blank List: ", List)

Blank List:
[]

# Creating a List of numbers

List = [10, 20, 30]


print("List of numbers: ")
print(List)

List of numbers:
[10, 20, 30]

# Creating a List of strings and accessing using index

List = ["Programming", "in", "Python"]


print("List Items: ")
print(List[0])
print(List[2])

List Items:
Programming
Python

# Creating a Multi-Dimensional List (By Nesting a list inside a List)

List = [['Programming', 'in'] , ['Python']]


print("Multi-Dimensional List: ")
print(List)

Multi-Dimensional List:
[['Programming', 'in'], ['Python']]
Python Programming Unit-3 Notes

A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.

` # Creating a List with the use of Numbers(Having duplicate values)


List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("List with the use of Numbers: ")
print(List)

List with the use of Numbers:


[1, 2, 4, 4, 3, 3, 3, 6, 5]

# Creating a List with mixed type of values (Having numbers and strings)

List = [1, 2, 'Programming', 4, 'in', 6, 'Python']


print("List with the use of Mixed Values: ")
print(List)

List with the use of Mixed Values:


[1, 2, 'Programming', 4, 'in', 6, 'Python']

Unlike strings, lists are mutable because you can change the order of items in a list or reassign an
item in a list. When the bracket operator appears on the left side of an assignment, it identifies the
element of the list that will be assigned.

# Updating a List elements (List are mutable)

Numbers = [17, 123]


print("Before: ", Numbers)
Numbers[1] = 5
print("After: ", Numbers)

Before: [17, 123]


After: [17, 5]

Using len() function we can find the length (no. of elements in list) of list.

# Creating a List of numbers and finding the length

List = [10, 20, 14]


print(len(List))
Python Programming Unit-3 Notes

List operation

# The + operator concatenates lists

a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)

[1, 2, 3, 4, 5, 6]

# The * operator repeats a list a given number of times

a = [1]
a=a*3
print(a)

[1, 1, 1]

List slices

# The slice operator

List = ['a', 'b', 'c', 'd', 'e', 'f']


print(List[1:3])
print(List[:4])
print(List[3:])

['b', 'c']
['a', 'b', 'c', 'd']
['d', 'e', 'f']

If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to
the end. So if you omit both, the slice is a copy of the whole list.
List = ['a', 'b', 'c', 'd', 'e', 'f']
print(List[:])

['a', 'b', 'c', 'd', 'e', 'f']


Python Programming Unit-3 Notes

A slice operator on the left side of an assignment can update multiple elements.

List = ['a', 'b', 'c', 'd', 'e', 'f']


List[1:3] = ['x', 'y']
print(List)

['a', 'x', 'y', 'd', 'e', 'f']

List methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

# append()

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")
fruits

['apple', 'banana', 'cherry', 'orange']


Python Programming Unit-3 Notes

# clear()

fruits = ['apple', 'banana', 'cherry', 'orange']


fruits.clear()
fruits

[]

# copy()

fruits = ['apple', 'banana', 'cherry', 'orange']


x = fruits.copy()
x

['apple', 'banana', 'cherry', 'orange']

# count()

fruits = ['apple', 'banana', 'cherry']


x = fruits.count("cherry")
x

#extend()

fruits = ['apple', 'banana', 'cherry']; cars = ['Ford', 'BMW', 'Volvo']


fruits.extend(cars)
fruits

['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']

#index()

fruits = ['apple', 'banana', 'cherry']


x = fruits.index("cherry")
x

2
Python Programming Unit-3 Notes

['apple', 'cherry']

#reverse()

fruits = ['apple', 'banana', 'cherry']


fruits.reverse()
fruits

['apple', 'cherry']

#sort()

cars = ['Ford', 'BMW', 'Volvo']


cars.sort()
cars

['BMW', 'Ford', 'Volvo']


Python Programming Unit-3 Notes

Tuples
A tuple is a sequence of immutable (A tuple is a collection which is ordered and unchangeable)
Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example

# creating a tuple

tup1 = ('ABC', 'pqr', 1000, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
print(tup1)
print(tup2)
print(tup3)

('ABC', 'pqr', 1000, 2000)


(1, 2, 3, 4, 5)
('a', 'b', 'c', 'd')

The empty tuple is written as two parentheses containing nothing

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only
one value

tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
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

# accessing a tuple

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])

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Python Programming Unit-3 Notes

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

# updating a tuple

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)

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting
together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example

# deleting a tuple

tup = ('ABC', 'pqr', 1997, 2000);


print(tup)
del tup;
print("After deleting tup : ")
print(tup)

This produces the following result. Note an exception raised, this is because after del tup tuple does
not exist any more

('ABC', 'pqr', 1997, 2000)


After deleting tup :
---------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-54-692273a13f26> in <module>
3deltup;
4print("After deleting tup : ")
----> 5print(tup)
NameError: name 'tup' is not defined
Python Programming Unit-3 Notes

Tuple Operations
Tuples respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new tuple, not a string

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3)+(4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1,2,3) True Membership

for x in (1, 2, 3): print(x) 123 Iteration

Indexing, Slicing, Matrices


Because tuples are sequences, indexing and slicing work the same way for tuples as they do for
strings. Assuming following input

L = ('spam', 'Spam', 'SPAM!')


Python Expression Results Description

L[2] 'SPAM!' Offsets start at zero

L[-2] 'Spam' Negative: count from the right

L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

Method Description

cmp(tuple1, tuple2) Compares elements of both tuples

len(tuple) Gives the total length of the tuple

max(tuple) Returns item from the tuple with max value

min(tuple) Returns item from the tuple with min value

tuple(seq) Converts a list into tuple


Tuple methods
Python includes the following tuple functions
Python Programming Unit-3 Notes

# cmp()

a = (1, 2, 1)
b = (1, 2, 2)
print(cmp(a, b))

-1

Here the third element in the first tuple is lower than the third element in the second tuple. Hence
returned -1.

# cmp()

c = ('a', 'b', 'e')


d = ('a', 'b', 'd')
print(cmp(c, d))

-1

Here the third element of the first tuple is greater than the third element of the second tuple. Hence
returned 1.

# len()

Max value
tuple1, element
tuple2 = (123,:zara
'xyz', 'zara'), (456, 'abc')
Max value tuple
print("First element : 700
length : ", len(tuple1))
print("Second tuple length : ", len(tuple2))

First tuple length : 3


Second tuple length : 2

# max()

tuple1, tuple2 = ('123', 'xyz', 'zara', 'abc'), (456, 700, 200)


print("Max value element : ", max(tuple1))
print("Max value element : ", max(tuple2))
Python Programming Unit-3 Notes

# tuple()

aList = [123, 'xyz', 'zara', 'abc']


aTuple = tuple(aList)
print("Tuple elements : ", aTuple)

Tuple elements : (123, 'xyz', 'zara', 'abc')

Dictionary
A dictionary is mutable and is another container type that canstore any number of Pythonobjects,
including other container types. Dictionaries consist of pairs (called items) of keys and their
corresponding values.
Python dictionaries are also known as associative arrays or hash tables. The general syntax of a
dictionary is as follows

dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

You can create dictionary in the following way as well:

dict1 = { 'abc': 456 };


dict2 = { 'abc': 123, 98.6: 37 };

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 string s, numbers, or tuples.
Accessing Values in Dictionary
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

# accessing a dictionary

dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


dict1['Name']: Zara", dict1['Name']);
print("dict1['Name']:
dict1['Age']: 7 ", dict1['Age']);
print("dict1['Age']:
dict1['Class']: First", dict1['Class']);
print("dict1['Class']:
Python Programming Unit-3 Notes

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as
follows

dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


print("dict1['Alice']: ", dict1['Alice'])

KeyError Traceback (most recent call last)


<ipython-input-58-d6f7f5c44745> in <module>
1 dict1 ={'Name':'Zara','Age':7,'Class':'First'};
----> 2print("dict1['Alice']: ", dict1['Alice'])
KeyError: 'Alice'

Updating Dictionary
You can update a dictionary by adding a new entry or item(i.e., a key-value pair), modifying an
existing entry, or deleting an existing entry as shown below in the simple example

# updating dictionary

dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


dict1['Age'] = 8; # update existing entry
dict1['School'] = "LJP"; # Add new entry
print ("dict1['Age']: ", dict1['Age'])
print ("dict1['School']: ", dict1['School'])

dict1['Age']: 8
dict1['School']: LJP

Deleting Dictionary Elements


To explicitly remove an entire dictionary, just use the del statement.

# deleting dictionary

dict1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};


del dict1['Name']; # remove entry with key 'Name'
dict1.clear(); # remove all entries in dict
del dict1 ; # delete entire dictionary
print("dict1['Age']: ", dict1['Age'])
print("dict1['School']: ", dict1['School'])
Python Programming Unit-3 Notes

Build-in Dictionary Functions & Methods


Python includes the following dictionary functions

Method Description

dict.clear() Removes all elements of dictionary dict

dict.copy() Returns a shallow copy of dictionary dict

dict.fromkeys() Create a new dictionary withkeys fromseq and


values set to value

dict.get(key, default=None) Returns the value of the item with the specified
key
Start Len : 2
End Len :0
dict.items() Returns a list of dict's (key, value) tuple pairs
# copy()
dict.keys() Returns list of dictionary dict's keys
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 dict.setdefault(key,
= dict1.copy() default=None) Similar to get(), but will set dict[key]=default if
print("New Dictionary : %s" % str(dict2)) key is not already indict

dict.update(dict2) Adds dictionary dict2's key-values pairs to dict


New Dictionary:{‘Name’:’Zara’,’Age’:7}
dict.values() Returns list of dictionary dict's values

# fromkeys()
# clear()
seq = ('name','age', 'sex')
dict = {'Name': 'Zara', 'Age': 7};
dict.fromkeys(seq)
print("Start
print("New Len : %d" %
Dictionary len(dict))
: %s" % str(dict))
dict.clear()
print("End Len : %d" % len(dict))
dict = dict.fromkeys(seq, 10)
print("New Dictionary : %s" % str(dict))

New Dictionary : {'name': None, 'age': None, 'sex': None}


New Dictionary : {'name': 10, 'age': 10, 'sex': 10}
Python Programming Unit-3 Notes

# get()

dict = {'Name': 'Zabra', 'Age': 7}


print("Value : %s" % dict.get('Age'))
print("Value : %s" % dict.get('Education', "Never"))

Value : 7
Value : Never

# items()

dict = {'Name': 'Zara', 'Age': 7}


print("Value : %s" % dict.items())

Value :dict_items([('Name', 'Zara'), ('Age', 7)])

# keys()

dict = {'Name': 'Zara', 'Age': 7}


print("Value : %s" % dict.keys())
Value :dict_keys(['Name', 'Age'])

# setdefault()

dict = {'Name': 'Zara', 'Age': 7}


print("Value : %s" % dict.setdefault('Age', None))
print("Value : %s" % dict.setdefault('Sex', None))

Value : 7
Value : None

# update()

dict1 = {'Name': 'Zara', 'Age': 7}


dict2 = {'Sex': 'female'}
dict1.update(dict2)
print("Value : %s" % dict1)

Value : {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}

#values()
Python Programming Unit-3 Notes

Set
Sets are used to store multiple items in a single variable.A set is a collection which is unordered,
unchangeable, and unindexed.Sets are written with curly brackets.
Set items are unchangeable, but you can remove items and add new items.

# creating set

thisset = {"apple", "banana", "cherry"}


print(thisset)

{'banana', 'apple', 'cherry'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Duplicates Not Allowed


Sets cannot have two items with the same value.

# creating set

thisset = {"apple", "banana", "cherry"}


print(thisset)

{'banana', 'apple', 'cherry'}

Set Items - Data Types


Set items can be of any data type.

# string, int and boolean data types

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
Python Programming Unit-3 Notes

A set can contain different data types.

# set with strings, integers and boolean values

set1 = {"abc", 34, True, 40, "male"}


print(set1)

{True, 'abc', 34, 40, 'male'}

Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set
items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

#True
loop through the set, and print the values

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x, end=",")

cherry,banana,apple,

# check if "apple" is present in the set:

thisset= {"apple", "banana", "cherry"}


print("apple" in thisset)

Add Items
Once a set is created, you cannot change its items, but you can add new items. To add one item to a
set use the add() method.

# add an item to a set, using the add() method

thisset = {"apple", "banana", "cherry"}


thisset.add("orange")
print(thisset)

{'cherry', 'orange', 'banana', 'apple'}

To add items from another set into the current set, use the update() method.

# add elements from tropical into thisset

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Python Programming Unit-3 Notes

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object (tuples, lists,
dictionaries etc.).

# add elements of a list to at set

# add elements from tropical into thisset

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)

{'cherry', 'kiwi', 'orange', 'banana', 'apple'}

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

# remove "apple" by using the remove() method

thisset= {"apple", "banana", "cherry"}


thisset.remove("apple")
print(thisset)

{'cherry', 'banana'}

# remove "apple" by using the discard() method

thisset= {"apple", "banana", "cherry"}


thisset.discard("apple")
print(thisset)

{'cherry', 'banana'}
Python Programming Unit-3 Notes

You can also use the pop() method to remove an item, but this method will remove the last item.
Remember that sets are unordered, so you will not know what item that gets removed. The return
value of the pop() method is the removed item.

##del keyword
remove willitem
the last delete the setthe
by using completely
pop() method

thisset=={"apple",
thisset {"apple","banana",
"banana","cherry"}
"cherry"}
del thisset
x = thisset.pop()
print(thisset)
print(x)
print(thisset)

cherry
{'banana', 'apple'}

#clear() method empties the set

thisset = {"apple", "banana", "cherry"}


thisset.clear()
print(thisset)

set()

NameError Traceback (most recent call last)


<ipython-input-24-2ec9feb8cb8a> in <module>
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)
NameError: name 'thisset' is not defined

Join Sets
There are several ways to join two or more sets in Python. You can use the union() method that
returns a new set containing all items from both sets, or the update() method that inserts all the items
from one set into another.
Python Programming Unit-3 Notes

#union() method returns a new set with all items from both sets

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

{1, 'c', 2, 3, 'a', 'b'}

#update() method inserts the items in set2 into set1

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set1.update(set2)
print(set1)

{1, 'c', 2, 3, 'a', 'b'}

Note: Both union() and update() will exclude any duplicate items.
Keep ONLY the Duplicates
The intersection_update() method will keep only the items that are present in both sets.

# keep the items that exist in both set x, and set y

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}

x.intersection_update(y)
print(x)

{'apple'}

The intersection() method will return a new set, that only contains the items that are present in both
sets.

# return a set that contains the items that exist in both set x, and set y

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
Python Programming Unit-3 Notes

Keep All, But NOT the Duplicates


The symmetric_difference_update() method will keep only the elements that are NOT present in
both sets.

# keep the items that are not present in both sets

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

{'google', 'cherry', 'microsoft', 'banana'}

The symmetric_difference() method will return a new set, that contains only the elements that are
NOT present in both sets.

# return a set that contains all items from both sets, except items that are present in both

x = {"apple", "banana", "cherry"}


y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)

{'google',
{'google', 'cherry',
'cherry', 'microsoft',
'microsoft', 'banana'}
'banana'}

You might also like