Python Notes
Python Notes
Python Notes
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
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']]
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.
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.
List = ['a', 'b', 'c', 'd', 'e', 'f']
print(List[:])
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()
# clear()
[]
# copy()
# count()
#extend()
#index()
2
Python Programming Unit-3 Notes
['apple', 'cherry']
#reverse()
['apple', 'cherry']
#sort()
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)
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
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
Method Description
# 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()
-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))
# max()
# tuple()
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
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
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
dict1['Age']: 8
dict1['School']: LJP
# deleting dictionary
Method Description
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
# 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))
# get()
Value : 7
Value : Never
# items()
# keys()
# setdefault()
Value : 7
Value : None
# update()
#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
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
# creating set
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
cherry,banana,apple,
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.
To add items from another set into the current set, use the update() method.
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
{'cherry', 'banana'}
{'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'}
set()
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
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.
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
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
{'google',
{'google', 'cherry',
'cherry', 'microsoft',
'microsoft', 'banana'}
'banana'}