Python UNIT 3
Python UNIT 3
Example:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
Output:
p
t
www.Jntufastupdates.com 1
2. Negative Indexing:
Python allows negative indexing for its sequences. The index of -1 refers to the last item,
-2 to the second last item and so on.
Example:
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-1])
print(my_tuple[-6])
Output:
t
p
3. Slicing:
We can access a range of items in a tuple by using the slicing operator colon (:).
Example:
my_tuple = ('p','r','o','g','r','a','m')
print(my_tuple[1:4])
print(my_tuple[:-5])
print(my_tuple[5:])
print(my_tuple[:])
Output:
('r', 'o', 'g')
('p', 'r')
('a', 'm')
('p', 'r', 'o', 'g', 'r', 'a', 'm')
www.Jntufastupdates.com 2
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.
Example:
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
Output:
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
www.Jntufastupdates.com 3
tuple3 = (tuple1, tuple2)
print(tuple3)
Output:
((0, 1, 2, 3), ('pragati', 'college'))
Output:
The index of e: 1
The index of i: 2
Reverse Indexing of Tuples in Python
Much similar to regular indexing, here, we use the index inside the square brackets to access the
elements, with only one difference, that is, we use the index in a reverse manner. Meaning, the
indexing of the elements would start from the last element. Here, we use indexes as −1, −2, −3,
and so on, where −1 represents the last element.
Example:
tup1= (‘Pragati’, ‘Engineering’, ‘College’)
print (tup1[-1])
www.Jntufastupdates.com 4
Output:
College
count() Parameters
The count() method takes a single parameter:
element - element whose count is to be found
Example:
vowels = ('a', 'e', 'i', 'o', 'i', 'o', 'e', 'i', 'u')
count = vowels.count('i')
print('The count of i is:', count)
count = vowels.count('p')
print('The count of p is:', count)
Output:
The count of i is: 3
The count of p is: 0
3.1.8. List comprehension and Tuples
List comprehensions were added with Python 2.0. Essentially, it is Python's way of
implementing a well-known notation for sets as used by mathematicians. In mathematics the
square numbers of the natural numbers are, for example, created by { x2 | x ∈ ℕ } or the set of
complex integers { (x,y) | x ∈ ℤ ∧ y ∈ ℤ }.
List comprehension is an elegant way to define and create list in Python. These lists have often
the qualities of sets, but are not in all cases sets.
List comprehension is a complete substitute for the lambda function as well as the functions
map(), filter() and reduce(). For most people the syntax of list comprehension is easier to be
grasped.
www.Jntufastupdates.com 5
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (10, 24, 26), (12, 16, 20), (15,
20, 25), (20, 21, 29)]
>>>
• We generally use tuples for heterogeneous (different) data types and lists for
homogeneous (similar) data types.
• Since tuples are immutable, iterating through a tuple is faster than with list. So there is a
slight performance boost.
• Tuples that contain immutable elements can be used as a key for a dictionary. With lists,
this is not possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it
remains write-protected.
www.Jntufastupdates.com 6
3.2. Dictionaries
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
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.
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'PEC', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Pragati', 2: 'Engineering', 3: 'College'}
www.Jntufastupdates.com 7
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Pragati', 2: 'Engineering', 3:'College'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Pragati'), (2, 'College')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
www.Jntufastupdates.com 8
There is also a method called get() that will also help in accessing the element from a
dictionary.
Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print(dict.get('Class'))
Output:
First
www.Jntufastupdates.com 9
Dictionary after adding 3 elements:
{0: 'Pragati', 2: 'Engineering', 3: 'College'}
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
www.Jntufastupdates.com 10
# Using del to remove a dict
# removes Mani
del test_dict['Mani']
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
www.Jntufastupdates.com 11
print ("The removed key's value is : " + str(removed_value))
print ('\r')
The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}
The removed key's value is : No Key found
print(people)
Output:
{1: {'name': 'John', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
In the above program, people is a nested dictionary. The internal dictionary 1 and 2 is
assigned to people. Here, both the dictionary have key name, age , sex with different values.
Now, we print the result of people.
Accessing elements of a Nested Dictionary:
To access element of a nested dictionary, we use indexing [] syntax in Python.
www.Jntufastupdates.com 12
Example:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
Output:
John
27
Male
Adding element to a Nested Dictionary
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}
people[3] = {}
people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'
print(people[3])
Output:
{'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}
In the above program, we create an empty dictionary 3 inside the dictionary people.
Then, we add the key:value pair i.e people[3]['Name'] = 'Luna' inside the dictionary 3. Similarly,
we do this for key age, sex and married one by one. When we print the people[3], we
get key:value pairs of dictionary 3.
Adding another dictionary to the nested dictionary:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}
www.Jntufastupdates.com 13
Deleting elements from a Nested Dictionary:
In Python, we use “ del “ statement to delete elements from nested dictionary.
Example:
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}
del people[3]['married']
del people[4]['married']
print(people[3])
print(people[4])
Output:
{'name': 'Luna', 'age': '24', 'sex': 'Female'}
{'name': 'Peter', 'age': '29', 'sex': 'Male'}
In the above program, we delete the key:value pairs of married from internal
dictionary 3 and 4. Then, we print the people[3] and people[4] to confirm changes.
How to delete dictionary from a nested dictionary?
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}
LIST DICTIONARY
List is a collection of index values pairs as that Dictionary is a hashed structure of key and
of array in C++. value pairs.
Dictionary is created by placing elements in {
List is created by placing elements in [
} as “key”:”value”, each key value pair is
] separated by commas “, “
separated by commas “, ”
The indices of list are integers starting from 0. The keys of dictionary can be of any data type.
www.Jntufastupdates.com 14
The elements are accessed via indices. The elements are accessed via key-values.
The order of the elements entered is
There is no guarantee for maintaining order.
maintained.
www.Jntufastupdates.com 15