Python Unit 3
Python Unit 3
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.
print("List Iteration")
l = ["ABC", "BCD", "CDE"]
for i in l:
print(i)
List Iteration
ABC
BCD
CDE
print("Tuple Iteration")
t = ("ABC", "BCD", "CDE")
for i in t:
print(i)
Tuple Iteration
ABC
BCD
CDE
print("String Iteration")
s = "ABCDE"
for i in s :
print(i)
String Iteration
A
B
C
D
E
1
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:
[]
List of numbers:
[10, 20, 30]
List Items:
Programming
Python
Multi-Dimensional List:
[['Programming', 'in'], ['Python']]
2
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 mixed type of values (Having numbers and strings)
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.
Using len() function we can find the length (no. of elements in list) of list.
3
Python Programming Unit-3 Notes
List operation
a = [1, 2, 3]
b = [4, 5, 6]
c=a+b
print(c)
[1, 2, 3, 4, 5, 6]
a = [1]
a=a*3
print(a)
[1, 1, 1]
List slices
['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.
4
Python Programming Unit-3 Notes
A slice operator on the left side of an assignment can update multiple elements.
List methods
Python has a set of built-in methods that you can use on lists.
Method Description
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
# append()
5
Python Programming Unit-3 Notes
# clear()
[]
# copy()
# count()
#extend()
fruits = ['apple', 'banana', 'cherry']
cars = ['Ford', 'BMW', 'Volvo']
fruits.extend(cars)
print(fruits)
#index()
6
Python Programming Unit-3 Notes
#insert()
#pop()
['apple', 'cherry']
#remove()
['apple', 'cherry']
#reverse()
#sort()
7
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 = ();
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[0]: physics
tup2[1:5]: (2, 3, 4, 5)
8
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
# deleting a tuple
This produces the following result. Note an exception raised, this is because after del tup tuple does
not exist any more
9
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
T=(1,2,3)
3 Length
print(len(T))
T=(1, 2, 3)+(4, 5, 6)
(1, 2, 3, 4, 5, 6) Concatenation
print(T)
T=('Hi!',)* 4
('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
Print(T)
T=(1,2,3)
True Membership
Print(3 in (T))
for x in (1, 2, 3): 1
print(x) 2 Iteration
3
len() function
len() is one of the built-in functions in python. It returns the number of items in an object.
When the object is a string, the len() function returns the number of characters in the string.
10
Python Programming Unit-3 Notes
# len()
Dictionary
A dictionary is mutable and is another container type that can store any number of Python objects,
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
d1 = { 'abc': 456 };
d2 = { '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
Name: Zara
Age: 7
Class: First
11
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
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
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print
(d1)
d1['Age'] = 8; # update existing entry
d1['School'] = "LJP"; # Add new entry
print ("d1['Age']: ", d1['Age'])
print ("d1['School']: ", d1['School'])
print (d1)
# deleting dictionary
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
print("Name:",d1['Name'])
del d1['Name']; # remove entry with key 'Name'
print(d1)
d1.clear(); # remove all entries in d1
print(d1)
del d1 ; # delete entire dictionary
print(d1)
12
Python Programming Unit-3 Notes
# clear()
Start Len: 2
End Len: 0
# copy()
# get()
Value: 7
Value: Never
None
13
Python Programming Unit-3 Notes
# items()
# keys()
#values()
# update()
14
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 and unindexed. Sets are written with curly brackets.
# creating set
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
# creating set
15
Python Programming Unit-3 Notes
Access Items
You cannot access items in a set by referring to an index or a key. But you can loop through the set
itemsusing a for loop, or ask if a specified value is present in a set, by using the in keyword.
cherry,banana,apple,
True
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 usethe add() method.
To add items from another set into the current set, use the update() method.
16
Python Programming Unit-3 Notes
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
{'cherry', 'banana'}
{'cherry', 'banana'}
17
Python Programming Unit-3 Notes
You can also use the pop() method to remove an item, but this method will remove the last item.
Rememberthat sets are unordered, so you will not know what item that gets removed. The return value
of the pop() method is the removed item.
cherry
{'banana', 'apple'}
set()
18
Python Programming Unit-3 Notes
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.
#union() method returns a new set with all items from both sets
Note: Both union() and update() will exclude any duplicate items.
19