Daf List in Python
Daf List in Python
Daf List in Python
Dr.M.Aniji
Data Structures in Python
joining lists,
replicating lists
slicing lists
Joining Two Lists
Joining two lists is very easy just like you perform addition
literally. The concentration
operator +, when used with two Lists, joins the two Lists.
Here is an example:
list7 = [1, 2, 4]
list8 = [5, 7, 8]
list7 + list8
[1, 2, 4, 5, 7, 8]
Replicating (i.e. Repeating) Lists
While the append( ) method adds just one element to the List, the
extend( ) method can add multiple elements to a List.
t1 = [‘a’, ‘b’, ‘c’]
t2 = [‘d’, ‘e’]
t1.extend (t2)
t1
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
t2
[‘d’, ‘e’]
insert( ) method
The pop( ) method removes an element from a given position in the List
and returns it. If no index is specified, this method removes and returns the
last item in the List.
Example:
t2 = [‘k’, ‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
ele1 = t2.pop()
ele1
‘k’
t2
[‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘u’]
ele2 = t2.pop( )
ele2
‘u’
t2
[‘a’, ‘e’, ‘i’, ‘p’, ‘q’]
remove( ) method
The pop( ) method removes an element whose position is given. But, what
if you know the value of the element to be removed, but you don’t know its
index (i.e. position) in the List.
Python provides the remove( ) method for this purpose. This method
removes the first occurrence of given item from the List.
Example:
t3 = [‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘a’, ‘q’, ‘p’]
t3.remove (‘q’)
t3
[‘a’, ‘e’, ‘i’,’p’, ‘a’, ‘q’, ‘p’]
clear( ) method
The clear( ) method removes all the items from the given List. The List
becomes an empty List after this method is applied to it.
Example:
t4 = [2, 4, 5, 7]
t4.clear( )
t4
[]
count( ) method
The sort( ) method sorts the items in a List in the ascending order by default. It
does not return anything. If we want this method to sort the items in the
descending order, we have to include the argument reverse = True.
Example:
t7 = [‘e’, ‘i’, ‘q’, ‘a’, ‘q’, ‘p’]
t7.sort( )
t7
[‘a’, ‘e’, ‘i’, ‘p’, ‘q’, ‘q’]
t7.sort (reverse = True)
t7
[‘q’, ‘q’, ‘p’, ‘i’, ‘e’, ‘a’]