I BSC Unit IV Python Notes
I BSC Unit IV Python Notes
:1
PYTHON PROGRAMMING
UNIT IV
Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list
operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple
– Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating
and Deleting Elements in a Dictionary – Dictionary Functions and Methods - Difference between
Lists and Dictionaries.
LISTS
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and
ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by
commas. The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.
# Creating a List
List = [] Output
print("Blank List: ")
print(List) Blank List:
# Creating a List of numbers []
List = [10, 20, 14]
print("\nList of numbers: ")
print(List) List of numbers:
print(list)
list[-1] = 25
print(list)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working with
the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
Let's see how the list responds to various operators.
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different
occasions.
Code
list1 = [12, 14, 16, 18, 20] Output:
l = list1 * 2 [12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
print(l)
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
list1 = [12, 14, 16, 18, 20] Output:
list2 = [9, 10, 32, 54, 86] [12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
l = list1 + list2
print(l)
3. Length
It is used to get the length of the list
Code Output:
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40] 9
len(list1)
4. Iteration
The for loop is used to iterate over the list elements.
Output:
Code 12
list1 = [12, 14, 16, 39, 40] 14
for i in list1: 16
39
print(i) 40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
list1 = [100, 200, 300, 400, 500]
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False
False
False
True
True
True
A tuple can contain any number of items, including ones with different data types (dictionary, string, float,
list, etc.).
Code: Output:
empty_tuple = () Empty tuple: ()
print("Empty tuple: ", empty_tuple) Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
int_tuple = (4, 6, 8, 10, 12, 14) A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
print("Tuple with integers: ", int_tuple)
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Tuples can be constructed without using parentheses. This is known as triple packing.
Code
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
print(tuple_)
print(type(tuple_) ) Output:
try: (4, 5.7, 'Tuples', ['Python', 'Tuples'])
tuple_[1] = 4.2 <class 'tuple'>
<class 'TypeError'>
except:
print(TypeError )
The construction of a tuple from a single member might be hard.
Simply adding parenthesis around the element is insufficient. To be recognised as a tuple, the element must
be followed by a comma.
Code
single_tuple = ("Tuple") Output:
print( type(single_tuple) ) <class 'str'>
single_tuple = ("Tuple",) <class 'tuple'>
print( type(single_tuple) ) <class '
single_tuple = "Tuple",
print( type(single_tuple) )
tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.
o Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try to access
an index from the tuple that is outside the range of the tuple index. In this case, an index above 4 will be out
of range.
We cannot give an index of a floating data type or other kinds because the index in Python must be an
integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1]) Output:
try: Python
print(tuple_[5]) Tuple
except Exception as e: tuple index out of range
tuple indices must be integers or
print(e)
slices, not float
try: l
print(tuple_[1.0]) 6
except Exception as e:
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:8
print(e)
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
print(nested_tuple[0][3])
print(nested_tuple[1][1])
o Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:
Element at -1 index: Collection
Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')
Slicing
In Python, tuple slicing is a common practise and the most popular method for programmers to handle
practical issues. Think about a Python tuple. To access a variety of elements in a tuple, you must slice it.
One approach is to use the colon as a straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
print("Elements between indices 1 and 3: ", tuple_[1:3])
print("Elements between indices 0 and -4: ", tuple_[:-4])
print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
Deleting a Tuple
A tuple's components cannot be altered, as was previously said. As a result, we are unable to get rid of or
remove tuple components.
However, a tuple can be totally deleted with the keyword del.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
del tuple_
try:
print(tuple_)
except Exception as e:
print(e)
Output:
'tuple' object does not support item deletion
name 'tuple_' is not defined
Repetition Tuples in Python
Code
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:9
Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Python Tuples is a collection of immutable objects that is more like to a list. Python offers a few ways to
work with tuples. These two approaches will be thoroughly covered in this essay with the aid of some
examples.
Examples of these methods are given below.
Count ( ) Method
The number of times the specified element occurs in the tuple is returned by the count () function of Tuple.
Code
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
res = [Link](2)
print('Count of 2 in T1 is:', res)
res = [Link]('java')
print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The first instance of the requested element from the tuple is returned by the Index() function.
Parameters:
The element to be looked for.
o begin (Optional): the index used as the starting point for searching
o final (optional): The last index up until which the search is conducted
o Index() Method
Code
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Tuple Membership Test
Using the in keyword, we can determine whether an item is present in the given tuple or not.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
print('Tuple' in tuple_)
print('Items' in tuple_)
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Output:
True
False
False
True
The list is better for performing operations, A Tuple data type is appropriate for
3
such as insertion and deletion. accessing the elements
Output:
{1: 'Python', 2: 'For', 3: 'Programming'}
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated
by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys
can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just
placing to curly braces{}.
Dict = {}
print("Empty Dictionary: ") Output:
print(Dict) Empty Dictionary:
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) {}
print("\nDictionary with the use of dict(): ") Dictionary with the use of dict():
print(Dict) {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dict = dict([(1, 'Geeks'), (2, 'For')]) Dictionary with each item as a pair:
print("\nDictionary with each item as a pair: ") {1: 'Geeks', 2: 'For'}
print(Dict)
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Adding elements to a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by
defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can
be done by using the built-in update() method. Nested key values can also be added to an existing
Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key
with the value is added to the Dictionary.
Dict = {}
print("Empty Dictionary: ") Output:
print(Dict) Empty Dictionary:
{}
Dict[0] = 'Geeks' Dictionary after adding 3 elements:
Dict[2] = 'For' {0: 'Geeks', 2: 'For', 3: 1}
Dict[3] = 1 Dictionary after adding 3 elements:
print("\nDictionary after adding 3 elements: ") {0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
print(Dict) Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Dict['Value_set'] = 2, 3, 4 Adding a Nested Key:
print("\nDictionary after adding 3 elements: ") {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
print(Dict) {'Nested': {'1': 'Life', '2': 'Geeks'}}}
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Dictionary =")
print(Dict)
#Deleting some of the Dictionar data
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:15
Output
Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}
Dictionary methods
Method Description
[Link]() Returns a list containing a tuple for each key value pair
[Link](key,default= set the key to the default value if the key is not specified in the
“None”) dictionary
[Link](key, default = “None”) used to get the value specified for the passed key.
# copy() method
dict2 = [Link]()
print(dict2)
# clear() method
[Link]()
print(dict1)
# get() method
print([Link](1))
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:16
# items() method
print([Link]())
# keys() method
print([Link]())
# pop() method
[Link](4)
print(dict2)
# popitem() method
[Link]()
print(dict2)
# update() method
[Link]({3: "Scala"})
print(dict2)
# values() method
print([Link]())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])
The indices of the list are integers starting The keys of the dictionary can be of any data
from 0. type.
List Dictionary
The elements are accessed via indices. The elements are accessed via key-value pairs.
Lists are orders, mutable, and can contain Dictionaries are unordered and mutable but they
duplicate values. cannot contain duplicate keys.
--------------------- X ----------------------