Chapter 3
Chapter 3
1 LIST
A list is a data type that allows you to store various types of data in it.
List is a compound data type which means you can have different-2 data types under a list, for
example we can have integer, float and string items in a same list.
The list will be ordered and there will be a definite count of it.
The elements are indexed according to a sequence and the indexing is done with 0 as the first
index.
Each element will have a distinct place in the sequence and if the same value occurs multiple times
in the sequence, each will be considered separate and distinct element.
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
# prints 300
print(numbers[5])
# prints 22
print(numbers[1])
Output:
11
300
22
Points to Note:
The index cannot be a float number.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[1.0])
Output:
TypeError: list indices must be integers or slices, not float
1. The index must be in range to avoid IndexError. The range of the index of a list having 10
elements is 0 to 9, if we go beyond 9 then we will get IndexError. However if we go below 0
then it would not cause issue in certain cases, we will discuss that in our next section.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Output:
IndexError: list index out of range
# a list of strings
my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
print(my_list[-1])
# prints "world"
print(my_list[-3])
# prints "hello"
print(my_list[-4])
Output:
bye
world
hello
Example 2:
my_list = ['p','r','o','b','e']
# Output: e
print(my_list[-1])
# Output: p
print(my_list[-5])
Example
n_list = ['P','Y','T','H','O','N','P','R','O','G']
#The search will start at index 1 (included) and end at index 3 (not included)
print(n_list[1:3])
print(n_list[:3])
print(n_list[3:])
print(n_list[:-5])
print(n_list[-3:])
print(n_list[-7:-3])
# Whole list
print(n_list[:])
Output:
['Y', 'T']
['P', 'Y', 'T']
['H', 'O', 'N', 'P', 'R', 'O', 'G']
['P', 'Y', 'T', 'H', 'O']
['R', 'O', 'G']
['H', 'O', 'N', 'P']
['P', 'Y', 'T', 'H', 'O', 'N', 'P', 'R', 'O', 'G']
['G', 'O', 'R', 'P', 'N', 'O', 'H', 'T', 'Y', 'P']
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(): Used for appending and adding elements to List. It is used to add elements to the
last position of List.
Syntax:
list.append(element)
Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]
insert(): Inserts an elements at specified position.
Syntax:
list.insert(position, element)
Note: Position mentioned should be within the range of List, as in this case between 0 and 4,
elsewise would throw IndexError.
Output:
['Mathematics', 'chemistry', 10087, 1997, 2000]
Syntax:
List1.extend(List2)
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
Output:
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
Syntax:
sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15
Output:
Traceback (most recent call last):
File "", line 1, in
sum(List)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Syntax:
List.count(element)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:
4
Syntax:
len(list_name)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:
10
index(): Returns the index of first occurrence. Start and End index are not necessary
parameters.
Syntax:
List.index(element[,start[,end]])
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output:
1
Another example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2,2))
Output:
4
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
Output:
4
After checking in index range 2 to 3
Traceback (most recent call last):
File "C:/Python/Python38/list_index.py", line 10, in <module>
print(List.index(2,2,4))
ValueError: 2 is not in list
min() : Calculates minimum of all the elements of List.
Syntax:
min(List)
Output:
1.054
Syntax:
max(List)
Output:
5.33
The sort() method sorts the items of a list in ascending or descending order.
Syntax:
list.sort([key,[Reverse]])
The sort() method doesn't return any value. Rather, it changes the original list.
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
Output
Sorted list: ['a', 'e', 'i', 'o', 'u']
sort in Descending order
The sort() method accepts a reverse parameter as an optional argument.
Setting reverse = True sorts the list in the descending order.
list.sort(reverse=True)
Example:
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# print vowels
print('Sorted list in Descending:', vowels)
Output
sorted()
If you want a function to return the sorted list rather than change the original list, use
sorted().
The simplest difference between sort() and sorted() is: sort() changes the list directly and
doesn't return any value, while sorted() doesn't change the list and returns the sorted list.
Syntax:
sorted([list[,key[,Reverse]]])
Key and reverse are not necessary parameter and reverse is set to False, if nothing is passed
through sorted().
Examples:
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
To Delete one or more elements, i.e. remove an element, many built in functions can be used, such
as pop() & remove() and keywords such as del.
pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs.
Output:
2.5
Output:
2.3
Output:
[4.445, 3, 5.33, 1.054, 2.5]
Output:
[2.3, 4.445, 5.33, 1.054, 2.5]
All Functions on List:-
List1 = [1,2,3,4,2,2,5,2]
List2 = [10,20,30]
List1.append(6)
print(List1)
List1.insert(2,10)
print(List1)
List2.extend(List1)
print(List2)
print(sum(List1))
print(List1.count(2))
print(len(List1))
print(List1.index(2))
print(min(List1))
print(max(List1))
List1.sort(reverse=True)
print(List1)
print(sorted(List1,reverse=True))
print(List1.pop(4))
print(List1)
del List1[2]
print(List1)
List1.remove(5)
print(List1)
3.2 Tuple
A tuple in Python is similar to a list. The difference between the two is that we cannot change the
elements of a tuple once it is assigned whereas, in a list, elements can be changed.
A] Creating a Tuple
A tuple is created by placing all the items (elements) inside parentheses (), separated by commas.
The parentheses are optional, however, it is a good practice to use them.
A tuple can have any number of items and they may be of different types (integer, float, list, string,
etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Otput
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
Note:
Example:
my_tuple = (10,20)
print(type(my_tuple)) # <class 'tuple'>
my_tuple = ("hello")
print(type(my_tuple)) # <class 'str'>
# Parentheses is optional
my_tuple = "hello",
print(type(my_tuple)) # <class 'tuple'>
Output:
<class 'tuple'>
<class 'int'>
<class 'tuple'>
<class 'str'>
<class 'tuple'>
<class 'tuple'>
B] Indexing
We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an element outside of
tuple (for example, 6, 7,...) will raise an IndexError.
The index must be an integer; so we cannot use float or other types. This will result in TypeError.
Likewise, nested tuples are accessed using nested indexing, as shown in the example below.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
# nested tuple
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4
Output
p
t
s
4
C] 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.
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])
Output
t
p
D] Slicing operation in tuples
We can access a range of items in a tuple by using the slicing operator - colon ":".
my_data = (11, 22, 33, 44, 55, 66, 77, 88, 99)
print(my_data)
Output:
Slicing can be best visualized by considering the index to be between the elements as shown below.
So if we want to access a range, we need the index that will slice the portion from the tuple.
E] Iteration through Tuple using for-loop
Iterating a tuple
# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")
# true
print(22 in my_data)
# false
print(2 in my_data)
# false
print(88 not in my_data)
# true
print(101 not in my_data)
Output:
(11, 22, 33, 44, 55, 66, 77, 88, 99)
True
False
False
True
# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
print(my_tuple)
Output
(4, 2, 3, [9, 5])
('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')
Output:
(0, 1, 2, 3, 'python', 'Arrow')
Nesting of Tuples
# Code for creating nested tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'geek')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'geek'))
Repetition in Tuples
# Code to create a tuple with repetition
tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')
3. Deleting a Tuple
We cannot change the elements in a tuple. That also means we cannot delete or remove items from
a tuple.
But deleting a tuple entirely is possible using the keyword del.
Error:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
Output
2
H] Tuple Methods
Methods that add items or remove items are not available with tuple. Only the following two
methods are available.
Python Tuple Method
Method Description
Output:
2
3
A set is created by placing all the items (elements) inside curly braces {}, separated by comma or
by using the built-in function set().
It can have any number of items and they may be of different types (integer, float, tuple, string etc.).
But a set cannot have a mutable element, like list, set or dictionary, as its element.
Example
# set of integers
my_set = {1, 2, 3}
print(my_set)
Output
{1, 2, 3}
{1.0, 'Hello', (1, 2, 3)}
In above example, Set contains immutable elements like tuple, float and string. We can not add list
element in set. See below example
Output:
{1, 2, 3, 4}
{1, 2, 3}
# initialize a with {}
a = {}
Output:
<class 'dict'>
<class 'set'>
Example1
my_set = {1,3}
my_set[0]
# if you run above code you will get an error TypeError: 'set' object does not support indexing
C] Adding element to set
We can add single element using the add() method and multiple elements using
the update() method. The update() method can take tuples, lists, strings or other sets as
its argument. In all cases, duplicates are avoided.
Example:
# initialize my_set
my_set = {1,3}
print(my_set)
# add an element
my_set.add(2)
print(my_set)
Output:
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}
D] Remove element from set:
discard / remove
A particular item can be removed from set using methods, discard() and remove().
The only difference between the two is that, while using discard() if the item does not exist in the
set, it remains unchanged.
But remove() will raise an error in such condition.
The following example will illustrate this.
Example 1:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
print(my_set)
Output:
{1, 3, 4, 5, 6}
{1, 3, 5, 6}
{1, 3, 5}
Example 2:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
Output:
{1, 3, 4, 5, 6}
{1, 3, 4, 5, 6}
Here the element 2 is not in the set, but discard will do nothing and set will remain unchanged.
Example 3:
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
my_set.remove(2)
print(my_set)
pop / clear
Similarly, we can remove and return an item using the pop() method.
Set being unordered, there is no way of determining which item will be popped.
It is completely arbitrary.
We can also remove all items from a set using clear().
Output:
Here the output may get changed every time as the sets are unordered and random element will be
popped every time.
E] Set Operations
Sets can be used to carry out mathematical set operations like union, intersection, difference and
symmetric difference. We can do this with operators or methods.
Let us consider the following two sets for the following operations.
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
1. Set Union
Example 1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B) # use | operator
Output:
{1, 2, 3, 4, 5, 6, 7, 8}
Example 2
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A)
print(B)
C=A.union(B) # use union function on B
print(C)
C= B.union(A) # use union function on B
print(C)
Output:
{1, 2, 3, 4, 5}
{4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5, 6, 7, 8}
2. Set Intersection
Exampe1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
print(A & B)
Output:
{4, 5}
Example2:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.intersection(B))
# use intersection function on B
print(B.intersection(A))
Output:
{4, 5}
{4, 5}
3. Set Difference
Difference of A and B (A - B) is a set of elements that are only in A but not in B. Similarly, B - A is a
set of element in B but not in A.
Difference is performed using - operator. Same can be accomplished using the method difference().
Example 1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
print(A - B)
Output:
{1, 2, 3}
Example: 2
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.difference(B))
print(B.difference(A))
Output:
{1, 2, 3}
{8, 6, 7}
4. Set Symmetric Difference
Symmetric Difference of A and B is a set of elements in both A and B except those that are common
in both.
Symmetric difference is performed using ^ operator.
Same can be accomplished using the method symmetric_difference().
Example 1:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
print(A ^ B)
Output:
{1, 2, 3, 6, 7, 8}
Example 2:
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A.symmetric_difference(B))
print(B.symmetric_difference(A)))
Output:
{1, 2, 3, 6, 7, 8}
{1, 2, 3, 6, 7, 8}
F] Other Set Operations
Set Membership Test
We can test if an item exists in a set or not, using the keyword in .
# initialize my_set
my_set = set("apple")
Output:
True
False
Output:
a
p
e
l
G] Different Python Set Methods
There are many set methods, some of which we have already used above. Here is a list
of all the methods that are available with set objects.
Method Description
intersection_update() Updates the set with the intersection of itself and another
symmetric_difference_
Updates a set with the symmetric difference of itself and another
update()
update() Updates the set with the union of itself and others
Output:
Set1 = {1, 2, 3, 4, 5}
Set2 = {3, 4, 5, 6, 7}
H] Deleting Set
Similar to lists and tuple, we can also delete an entire set by using keyword “del” followed by set to
be deleted.
Example:
set1={10,20,30}
print(“Initially set1 contains : “ set1)
del set1
print(“After deletion, set1 contains”, set1)
A] Creating a Dictionary
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces,
separated by ‘comma’.
Dictionary holds a pair of values, one being the Key and the other corresponding pair element
being its Key:value.
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
Output:
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by
just placing to curly braces{}.
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output:
There is also a method called get() that will also help in acessing the element from a dictionary.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Example 1:
Output:
1
3
9
5
7
Here i refers to key (index) of dictionary by default. If we want to print values of associated keys,
we use [] operator as follows.
Example 2:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
Output:
1
9
81
25
49
Python Dictionary Methods
Methods that are available with dictionary are tabulated below. Some of them have
already been used in the above examples
Method Description
Return a new dictionary with keys from seq and value equal
fromkeys(seq[, v])
to v (defaults to None).
Remove the item with key and return its value or d if key is
pop(key[,d]) not found. If d is not provided and key is not found, raises
KeyError.
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output:
We can append one dictionary with another dictionary using update ( ) function.
# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Dict2 = {'Nakul':'study','Navnath':'kharda'}
print ("Initially Dictionary contains",Dict1)
Dict1.update(Dict2)
print("After updation Dictionary contains",Dict1)
Output:
b) Assignment operator:
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
a) pop( )
We can remove a particular item in a dictionary by using the method pop(). This method removes
an item with the provided key and returns the value.
b) popitem()
The method, popitem() can be used to remove and return an arbitrary item (key, value)
form the dictionary.
c) clear()
All the items can be removed at once using the clear() method.
d) del ()
We can also use the del keyword to remove individual items or the entire dictionary
itself.
# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}
print(squares)
print(squares)
print(squares)
print(squares)
16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}
Example1:
# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print ("All the keys in dictionary are", Dict1.keys())
print ("All the values in dictionary are",Dict1.values())
Output:
# Creating a Dictionary
Dict1 = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(Dict1.__len__())
Output:
3