Python LAB 2
Python LAB 2
Python LAB 2
In the previous blog, we saw how we can use the variables and data types in python. We
also investigated some useful functions related to data types and variables.
Python is a powerful scripting language. It has many built-in data structures available for
use. These structures are so powerful in handling the data, yet they are simple to
implement.
These basic structures are of four types – list, tuple, dictionary and set.
Lists in Python
Lists are in-built n python. These are mutable, so items can be added or removed from
them without altering their original contents, and elements can be accessed through
index.
They are so general that they can be used to store any type of object, from strings to
numbers, even the objects also. Moreover, it is not required to have all the elements of the
same type, A list can have elements of different types.
For Example:
?
1 # An empty list
2 empty_list = []
3 # List with same type of elements
4 same_type_list = [‘1’, ‘3’, ‘7’, ‘10’]
5 # List with different types of elements
diff_type_list = [‘John’, ‘Dev’, 1.90, True]
6
Now we know how to initialize the variable with list. Let’s see some basic operations.
For Example:
?
1 # Printing the length of the list
2 some_list = ['k', 'u', 'm', 'a', 'r']
3 print(len(some_list))
4 # Traversal of list
5 for i in range(len(some_list)):
print(some_list[i])
6
?
1
# Output
2
3 5
4 k
5 u
6 m
a
7 r
8
2. max(list) – It returns the item in the given list with the highest value, if there is no tie
then it returns an error.
For Example:
?
1 # Printing the maximum of the number stored in list
2 num_list = [1, 2, 3, 4, 5, 12, 78, 900, 100]
3 print(max(num_list))
4
?
1 # Output
2
3 900
3. min(list) – it returns the item in the given list with lowest value, if there is no tie then it
returns an error
For Example:
?
1 # Printing the minimum of the number stored in list
2 num_list = [1,2,3,4,5,12,78,900,100]
3 print(min(num_list))
?
1 # Output
2
3 1
4. sort(list) – This function sorts through all these data and puts them in
ascending/descending order by default but if key parameter is passes it sorts the list
based on the evaluation of the function on the elements.
For example:
?
1 num_list = [1,2,3,4,5,12,78,900,100]
2 print(num_list)
3 num_list.sort()
4 print(num_list)
5 num_list.sort(reverse = True)
print(num_list)
6
?
1 Output:
2
3 [1, 2, 3, 4, 5, 12, 78, 900, 100]
4 [1, 2, 3, 4, 5, 12, 78, 100, 900]
5 [900, 100, 78, 12, 5, 4, 3, 2, 1]
5. map(function, sequence) – This function here applies a function on each element of the
list. The syntax is given by map(fun, iter). Here ‘fun’ is the function that is supposed to be
applied on every element of ‘iter’.
For Example:
?
1 def square(n):
2 return n * n
3
4 numbers = [1, 2, 3, 4]
5 result = map(square, numbers)
print(list(result))
6
?
1 output:
2 [1, 4, 9, 16]
There are so many other functions are there for lists. Now let’s see what tuples are.
Python tuples
They can be created by simply declaring a tuple within parentheses, (), or by converting
any sequence into a tuple using the built-in constructor tuple().
?
1
# Creating an empty tuple
2 empty_tuple = ()
3
4 seq_set = {1,2,3}
5 seq_list = [2,3,4,5]
6 print(type(seq))
7 print(type(seq_list))
# Converting set into tuple
8 seq_set_tuple = tuple(seq_set)
9
?
01 Output:
<class 'set'> <class 'list'>
02
# Creating an empty tuple
03 empty_tuple = ()
04
05 seq_set = {1, 2, 3}
06 seq_list = [2, 3, 4, 5]
07 print(type(seq_set))
print(type(seq_list))
08 # Converting set into tuple
09 seq_set_tuple = tuple(seq_set)
10 print(type(seq_set_tuple))
11
12 output:
13
14 <class 'set'> <class 'list'> <class 'tuple'>
15
16
Tuples are like lists with the difference that tuples are immutable. Then why do we use the
tuples.
Like list, a tuple is also a sequence of data elements, which are not necessarily of the same
type.
For Example:
?
1 # Tuple with same type of elements
2 same_type_list = ('1', '3', '7', '10')
3 print(same_type_list)
?
1 Output:
2
3 ('1', '3', '7', '10')
?
1 # List with different types of elements
2 diff_type_list = ('John', 'Dev', 1.90, True)
3 print(diff_type_list)
?
1 # Output
2
3 ('John', 'Dev', 1.9, True)
It can also be defined with the built-in function set([iterable]). This function takes as
argument an iterable (i.e., any type of sequence, collection, or iterator), returning a set
containing unique items from the input (duplicated elements are removed).
For Example:
?
1 # Create a Set using
2 # A string
3 print(set('Dev'))
?
1 Output:
2 {'e', 'v', 'D'}
?
1 # a list
2 set(['Mayank', 'Vardhman', 'Mukesh', 'Mukesh'])
?
1 Output:
2 {'Mayank', 'Mukesh', 'Vardhman'}
?
1 # A tuple
2 set(('Lucknow', 'Kanpur', 'India'))
?
1 Output:
2 {'India', 'Kanpur', 'Lucknow'}
?
1 # a dictionary
2 set({'Sulphur': 16, 'Helium': 2, 'Carbon': 6, 'Oxygen': 8})
?
1 Output:
2 {'Carbon', 'Helium', 'Oxygen', 'Sulphur'}
Now, we know how to create Sets. Let’s see what the common operations in sets are.
The method works in-place and modifies the set and returns ‘None’.
For Example:
?
1 locations = set(('Lucknow','kanpur','India'))
2 locations.add('Delhi')
3 print(locations)
?
1 Output:
2 {'India', 'Delhi', 'Lucknow', 'kanpur'}
In Python sets, we cannot insert an element in a particular index because it is not ordered.
There are three methods using which you can perform the removal of an element from a
set.
set.remove(element)
set.descard(element)
set.pop()
set.remove(element)
?
1 locations = set(('Lucknow', 'kanpur', 'India'))
2 #Removes Lucknow from the set
3 locations.remove('Lucknow')
4 print(locations)
?
1 Output:
2 {'India', 'kanpur'}
set.discard(element)
?
1 locations = set(('Lucknow', 'kanpur', 'India'))
2 # Removes ‘Lucknow’ from the set
3 locations.discard('Lucknow')
4 print(locations)
?
1 Output:
2 {'India', 'kanpur'}
As you can see that both the ‘remove’ and ‘discard’ method work in-place and modify the
same set on which they are getting called. They return ‘None’.
The only difference that is there in the ‘remove’ and ‘discard’ function is that ‘remove’
function throw an exception (KeyError) is raised, if ‘element’ is not present in set. The
exception is not thrown in case of ‘discard’.
set.pop()
?
1 locations = set(("Lucknow", 'Kanpur', 'India'))
2 # Removes ‘Lucknow’ from the set
3 removed_location = locations.pop()
4 print(locations)
print(removed_location)
5
?
1 Output:
2 {'Kanpur', 'Lucknow'}
3 India
‘pop’ function does not take any arguments and removes any arbitrary element from set.
It also works in-place but unlike other methods it returns the removed element.
So, we have covered lists, tuples, and Python sets. Now, finally let’s see how things work in
python dictionaries.
Dictionaries in Python
Python dictionaries are a fundamental data type for data storage and retrieval.
The dictionary is a built-in data structure that stores key:value pairs and can be accessed
by either the key or the value. Python dictionaries are unordered, and keys cannot be
negative integers. On top of that, while keys must be immutable, values do not have to be.
The syntax for creating a dictionary is to place two square brackets after any sequence of
characters followed by a colon (e.g., {‘a’: ‘b’}); if you are passing in more than one sequence
then you need to put them in separate sets of brackets (e.g., {‘a’: ‘b’, ‘c’: ‘d’}).
For Example:
?
1 # Creating an empty Dictionary
2 Dictionary = {}
3 print("Empty Dictionary: ")
4 print(Dictionary)
?
1 Output:
2 Empty Dictionary: {}
?
1 # Creating a Dictionary
2 # With dict() method
3 Dictionary = dict({1: 'Hello', 2: 'World', 3: '!!!'})
4 print("\nDictionary by using dict() method: ")
print(Dictionary)
5
?
1 Output:
2 Dictionary by using dict() method:
3 1: 'Hello', 2: 'World', 3: '!!!'}
Now, let’s create the dictionary using a list of tuples of key and value pair:
?
1 # Creating a Dictionary
2 Dict = dict([(1, 'Hello'), (2, 'World')])
3 print("\nDictionary by using list of tuples of key and value as a pair: ")
4 print(Dict)
?
1 Output:
2 Dictionary by using list of tuples of key and value as a pair:
3 {1: 'Hello', 2: 'World'}
Let’s see briefly what are the methods that are present in dictionary of Python.
Difference Between Python sets and dictionaries
A set is a collection of values, not necessarily of the same type, whereas a dictionary
stores key-value pairs.
Python sets are collections of data that do not have any order or keys. A set does not store
any data about its members other than their identity. Dictionaries are collections that
map unique keys to values. Furthermore, dictionaries store information about their
members including the key and value pair.
So, we built some basic understanding about Lists, Tuples, Sets and Dictionaries in Python.
We also investigated some functions and their implementations.