1 (List and Tuple)
1 (List and Tuple)
1 (List and Tuple)
(KNC- 302)
UNIT 3
We can access each element of a list in python by their assigned index. In python starting index of
list sequence is 0 and ending index is (if N elements are there) N-1.
print(list1[1:3]) [2,3]
Each element in list is assigned an index in positive indexing we have index from 0 to
end of the list and in negative indexing we have index from -N(if elemts are N) till -1.
As shown in above examples the work of accessing elements is manual. We can also
access or assign elements through loops.
# assigning elements to list
list1 =[]
for i in range(0, 11):
list1.append(i)
[1, 2, 5, 4
[1, 2, 5, 4, 6]
# updating [1, 2, 5, 4, 6, 1, 2, 3]
list1[2]= 5
print(list1)
# appending
list1.append(6)
print(list1)
# extending
list1.extend([1, 2, 3])
print(list1)
Deleting elements of list :
We can delete elements in lists by making use of del function. In this you need to
specify the position of element that is the index of the element and that element will
be deleted from the list and index will be updated.
list1 = [1, 2, 3, 4, 5]
print(list1)
# deleting element
del list1[2]
print(list1)
map
map is another useful function available in Python. Suppose you have a list of characters and you
want to convert all of them to int in one go, then you can use 'map'. Let's see an example of map:
a = ['1','2','3','4']
b = list(map(int,a))
print(b)
index is a function which gives us the index of an element of a list. It will be clear
from the example given below
Print a.index(‘2’)
Assigning and Copying Lists
This issue does not apply to strings and tuples, since they are immutable and therefore
cannot be modified.
... temperatures = [ 88, 94, 97, 89, 101, 98, 102, 95, 100]
... [t for t in temperatures if t >=100]
???
... [(t -32) * 5/9 for t in temperatures]
Tuple
In Python, a tuple is similar to List except that the objects in tuple are immutable
which means we cannot change the elements of a tuple once assigned. On the other
hand, we can change the elements of a list.
Tuple vs List
1. The elements of a list are mutable whereas the elements of a tuple are
immutable.
2. When we do not want to change the data over time, the tuple is a preferred
data type whereas when we need to change the data in future, list would be a wise
option.
3. Iterating over the elements of a tuple is faster compared to iterating over a list.
4. Elements of a tuple are enclosed in parenthesis whereas the elements of list are
enclosed in square bracket.
Examples
my_data2 = (1, 2.8, "Hello World") or
My_data2=(1,2.8,’hello world’
print(my_data2)
# empty tuple
my_data = ()
print(my_data4)
Iterating a tuple
# tuple of fruits
my_tuple = ("Apple", "Orange", "Grapes", "Banana")
# iterating over tuple elements
for fruit in my_tuple: print(fruit)