List Tuple Dictionary
List Tuple Dictionary
DICTIONARY
Lists
Like a String, List also is,
sequence data type.
In a string we have only
characters but a list consists of
data of multiple data types
It is an ordered set of values
enclosed in square brackets [].
We can use index in square
brackets []
Values in the list are called
elements or items.
List index works the same way
as String index :
An integer value/expression can
be used as index
An Index Error appears, if you
try and access element that
does not exist in the list
IndexError: list index out of
range
An index can have a negative
value, in that case counting
happens from the end of the
list.
List Examples
L=[1,2,3,4]
i=0
while i < 4:
print (L[i])
i+=1
Output
1234
Traversing a List
Using for loop
L=[1,2,3,4,5]
L1=[1,2,3,4,5]
for i in L: for i in range (5):
print(i) print(L1[i])
Output: Output:
12345 12345
List Slices
Examples
>>> L=[10,20,30,40,50]
>>> print(L[1:4])
[20, 30, 40] #print elements 1st index to 3rd index
>>> print(L[3:])
[40, 50] #print elements from 3rd index
onwards
>>> print(L[:3])
[10, 20, 30] #print elements 0th index to 2nd index
Example
>>> l1=[10,20,30]
>>> l2=[100,200,300]
>>> l1.extend(l2)
>>> print(l1)
[10, 20, 30, 100, 200, 300]
>>> print(l2)
[100, 200, 300]
pop , del and remove functions
>>> l=[10,20,30,40,50]
>>> l.pop() #last index elements
popped
50
>>> l.pop(1) # using list index
20
>>> l.remove(10) #using element
>>> print(l)
[30, 40]
Example-del()
>>> l=[1,2,3,4,5,6,7,8]
>>> del l[2:5] #using
range
>>> print(l)
[1, 2, 6, 7, 8]
insert ()method
used to add element(s) in
between
Example
>>> l=[10,20,30,40,50]
>>> l.insert(2,25)
>>> print(l)
[10, 20, 25, 30, 40, 50]
sort() and reverse() method
Example:
>>> l=[10,8,4,7,3]
>>> l.sort()
>>> print(l)
[3, 4, 7, 8, 10]
>>> l.reverse()
>>> print(l)
[10, 8, 7, 4, 3]
Linear search program
Tuples
We saw earlier that a list is
an ordered mutable collection
. There’s also an
ordered immutable collection.
In Python these are called
tuples and look very similar to
lists, but typically written with ()
instead of []:
a_list = [1, 'two', 3.0]
a_tuple = (1, 'two', 3.0)
Similar to how we used list before,
you can also create a tuple.
The difference being that tuples
are immutable. This means no
assignment, append, insert, pop,
etc. Everything else works as it
did with lists: indexing, getting
the length etc.
Like lists, all of the common
sequence operations are
available.
Example of Tuple:
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple ) # Prints complete list
print (tuple[0]) # Prints first element of the list
print (tuple[1:3]) # Prints elements starting from 2nd till
3rd
print (tuple[2:]) # Prints elements starting from 3rd
element
print (tinytuple * 2) # Prints list two times
print 9tuple + tinytuple) # Prints concatenated lists
The following code is invalid with tuple,
because we attempted to update a
tuple, which is not allowed. Similar case
is possible with lists −