List, Dictionary, Tuple - Day 4
List, Dictionary, Tuple - Day 4
The list is written as a list of comma-separated values (items) between square brackets. Items in a list need
not be of the same type. List is a mutable data type means elements can be changed.
The first element of the list is stored at index 0 and the last element is stored at the location n-1 where n is
the size of list. Also when a list is printed then no need to print each element separately we just need to
pass name of list to print() function.
An Example:
l1 = [1,2,3,4,5];
print(l1)
print("The first element is",l1[0])
print("The last element is",l1[4])
print("The last element is",l1[-1])
print("The last three elements are",l1[2:])
print("The first three elements are",l1[:3])
l2 = ["python",1990,3.6];
print('\n',l2)
To print a range of elements from a list we can use slicing operator same as we have used with string.
An Example
ls = ["PMD",2018,"Python","MySql","Django"];
print("Elements at index 0,1 are",ls[0:2])
print("Elements at index 2,3,4 are",ls[2:5])
Let us take a look at some operations that can be performed on list like
1. We can delete an element from list using del statement.
2. We can concatenate two or more list using + operator
3. We can use * operator with list to repeat the list
4. We can use in operator to find an element in list
5. We can iterate through the elements of list
An Example
ls1 = [1,2,3,4]
print("The list ls1 is",ls1)
del ls1[0];
print("The list ls1 after removing first element is",ls1,"\n")
ls2 = [5,6,7]
print("The list ls2 is",ls2)
ls1 = ls1 + ls2
print("The list ls1 after concatenating ls2 is",ls1,"\n")
ls3 = [8,9]
print("The list ls3 is",ls3)
ls3 = ls3*2
print("The list ls3 after repeatation is",ls3,"\n")
ls4 = ["Java","MySql","Networking"]
print("\nThe elements of ls4 ")
for i in ls4:
print(i)
An Example
my_list = ["Java",["1.7","1.8","1.9"],"Python",["3.7","3.8"],"Android
Studio",["2.7","3.0","3.1"]]
print(my_list[0])
print(my_list[1][0])
print(my_list[1][2])
print(my_list[2])
print(my_list[3][0])
print(my_list[3][1])
print(my_list[4])
print(my_list[5][0])
print(my_list[5][1])
The code given above will produce following output
Java
1.7
1.9
Python
3.7
3.8
Android Studio
2.7
3.0
Function Description
append(item) The append() method takes a single item and adds it to the end of the list. The
item can be numbers, strings, another list, dictionary etc. It doesn't return any
value.
clear() clear() method only empties the given list.
count(element) The count() method returns the number of occurrences of an element in a list.
extend(list2) the extend() method takes a single argument (a list) and adds it to the end. This
method can also be used with tuple and set. It doesn't return any value.
index(element) The index() method returns the index of the element in the list. If not found, it raises
a ValueError exception indicating the element is not in the list.
insert(index, insert() method inserts the element to the list. It doesn't return any value.
element) Index position where element needs to be inserted
Element this is the element to be inserted in the list
iter(object[, The iter() method returns an iterator for the given object.
sentinel]) object object whose iterator has to be created (can be sets, tuples,
etc.)
sentinel special value that is used to represent the end of a sequence
len(list) The len() function returns the number of items of an object. Failing to pass an
argument or passing an invalid argument will raise a TypeError exception.
An Example
l1 = [1,2,6,5];
print("Total elements in l1 is",len(l1))
print("The sum of l1 is",sum(l1))
print("The mean of l1 is",sum(l1)/len(l1))
l2 = ["Java","MySQL","Python"]
print("\nThe minimum of l2 is",min(l2))
print("The maximum of l2 is",max(l2))
Total elements in l1 is 4
The sum of l1 is 14
The mean of l1 is 3.5
We can append elements in a list using append() method. This method can be used to take input
An Example:
l1 = [] #An empty list
while True:
x = int(input("Please enter element to be added to list, 0 to stop "))
if x == 0:
break
l1.append(x);
print("list is ",l1)
Java,Python,Android
Apart from that to convert the String into list we have split method
print(“Metier TechTutors”.split())
[‘Metier’,’TechTutors’]
iter_obj = iter(iterable)
# infinite loop
while True:
try:
# get the next item
element = next(iter_obj)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
So internally, the for loop creates an iterator object, iter_obj by calling iter() on the iterable. Ironically, this
for loop is actually an infinite while loop. We will look at exception handling later.
Dictionary in python
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. 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.
An Example
dic = {"Company":"HP", "Model":"AT2216TU","Price":28700}
print(dic)
print("dic[Company] = ",dic["Company"])
print("dic[Model] = ",dic["Model"])
print("dic[Price] = ",dic["Price"])
del dic["Price"]
print("After deletion dic is",dic)
Tuples in Python
A tuple is a sequence of Python objects. It is similar to the list with the difference that the tuples cannot be
changed means it is immutable but list is mutable. tuples use parentheses, whereas lists use square
brackets. Actually it is not compulsory to use parentheses with tuples because it can also be written without
that.
An Example
tup1 = () #An empty tuple
tupi = (50) #it’s an integer
tup2 = (50,) #A tuple with single element, don't forgot to use comma
tup3 = (1, 2, 3, 4, 5) # is same as tup3 = 1, 2, 3, 4, 5
print(tup3)
print(tup3[0])
print(tup3[-1])
print(tup3[1:4])
(1, 2, 3, 4, 5)
1
5
(2, 3, 4)
As we have already discussed that updating tuple is not possible because it is immutable. So the code
given below will produce error
Similarly deleting individual element from tuple is not possible, although we can delete whole tuple using
del keyword.