Python Programming – List Functions And Methods

You can learn about List Manipulation in Python Programs with Outputs helped you to understand the language better.

Python Programming – List Functions And Methods

Python provides various methods that operate on lists. For example, append ( ) adds a new element to the end of a list, extend ( ) takes a list as an argument and appends all of the elements, sort( ) arranges the elements of the list from low to high, and pop( ) modifies the list and returns the element that was removed.
Every list object that you create in Python is actually an instance of the List class. The syntax of using it is discussed below:
<listObject>.<method name>( )

len( )
The built-in len( ) function is used to get the length of list.
>>> 1st = [ ‘ a ‘ , ‘ b ‘ , ‘ c ‘ , ‘ d ‘ ]
>>> len ( a )
4
It is possible to nest lists (create list containing other lists), for example:
>>> q = [ 2 , 3 ]
>>> p = [ 1 , q , 4 ]
>>> len(p)
3

  • len( ) returns the number of items in the list.

Let’s Try

Find and write the output of the following Python codes:

a = [ ” Red ” , ” Blue ” , ” Grenn ” ]
print ( len ( a ) )
List = [ 1 , 2 , 3 , 3 , 2 , 1 ]
print ( len ( List ) )

count( )

To find out the number of times a value occurs in a list, use the count(value) method.
>>> basket = [ ‘ apple ‘ , ‘ banana ‘ , ‘ orange ‘ , ‘ apple ‘ ]
>>> basket.count ( ‘ apple ‘ )
2
>>> a_list = [ 47 , ” 47 ” , 47 , 4747]
>>> a_list.count ( 47 )
2

  • count( ) returns the number of occurrences of the specified object in the list.

Let’s Try

Find and write the output of the following Python codes:

>>> a_list = [ ‘ she ‘ , ‘ sells ‘ , ‘ sea-shells ‘ ]
>>> a_list.count ( ‘ she ‘ )
n = [ 1 , 1 , 2 , 3 , 4 , 4 , 4 , 5 ]
print ( n . count ( 4 ) )
print ( n . count ( 1 ) )
print ( n . count ( 2 ) )
print ( n . count ( 6 ) )

Example
Demo of List count using count( ) Method.

# Python List count using count() Method
colours = [ ‘ Red ‘ , ‘ Orange ‘ , ‘ Green ‘ , ‘ Blue ‘ , ‘ Red ‘ , ‘ Blue ‘ ]
numbers = [7, 2, -5, 0, 7, -1, 2, 7]print ( ” Original List : ” , colours )
print ( ‘ Number of Times Colour Red is repeated = ‘, colours . count( ‘ Red ‘ ) )
print ( ‘ Number of Times Colour Blue is repeated = ‘, colours . count ( ‘ Blue ‘ ) )
print ( ‘ Number of Times Colour Green is repeated ‘, colours . count ( ‘ Green ‘ ) )print ( ” \ n Original number List : “, numbers )
print ( ‘ Number of Times no.7 is repeated = ‘, numbers . count ( 7 ) )
print ( ‘ Number of Times no. 2 is repeated = ‘, numbers .count ( 2 ) )
print ( ‘ Number of Times no. 0 is repeated = ‘, numbers . count ( 0 ) )RUN
>>>
Original List : [ ‘ Red ‘ , ‘ Orange ‘ , ‘ Green ‘ , ‘ Blue ‘ , ‘ Red ‘ , ‘ Blue ‘ ]
Number of Times Colour Red is repeated = 2
Number of Times Colour Blue is repeated = 2
Number of Times Colour Green is repeated 1Original number List : [7, 2, -5, 0, 7, -1, 2, 7]
Number of Times no.7 is repeated = 3
Number of Times no. 2 is repeated = 2
Number of Times no. 0 is repeated = 1
>>>

append( )

To add an item to the end of a list, use the append() method. This method changes the list in place. The syntax of the append( ) method is:
list.append(item)
The item can be numbers, strings, another list, dic-tionary etc.
This example adds the string ‘apple’ to a list:
>>> basket = [‘apple’, ‘banana’, ‘or-ange’]
>>> basket.append(‘apple’)
>>> basket
[‘apple’, ‘banana’, ‘orange’, ‘apple’]
This example adds the integer 444 to a list:
>>> items = [111, 222, 333]
>>> items.append(444)
>>> items
[111, 222, 333, 444].
Remember, list methods modify the target list in place. They do not return a new list:
>>> a = [‘a’, ‘b’]
>>> x = a.append(17)
>>> print(x)
None
>>> a
[‘a’, ‘b’, 17]
Also, append() allows you to append a string as a single entity:
>>> a = [‘a’, ‘b’]
>>> a.append(‘cat’)
>>> a
[‘a’, ‘b’, ‘cat’]

Let’s Try

Find and write the output of the following Python codes:

a = [ ” Red ” , ” Blue ” ]
print ( a )
a . append ( ” Green ” )
print ( a )
odd = [1 , 3 , 5 ]
odd.append (7)
print (odd)
  • append( ) adds an item to the end of the list.

extend( )

To add the items of one list i.e., iterable object to an existing list, use the extend( ) method. In other words, all the items of a list are added at the end of the already created list. The syntax is:
list.extend(list2)
Here list is primary list, which will be extended and list2 will be added to list.
This example adds elements of list y to x.
>>> x = [‘apple’, ‘banana’, ‘orange’]
>>> y= [‘pear’, ‘mango’]
>>> x.extend(y)
>>> x
[‘apple’, ‘banana’, ‘orange’, ‘pear’, ‘mango’ ]
This example adds elements of list b to a.
>>> a = [11, 22, 33,]
>>> b = [44, 55]
>>> a.extend ( b )
>>> a
[11, 22, 33, 44, 55]
If the iterable object is a string, each character is added individually. This example adds each charac-ter of the string ‘pear’.
>>> x = [‘apple’, ‘banana’, ‘orange’]
>>> x.extend(‘pear’)
>>> x
[‘apple’, ‘apple’, ‘banana’, ‘orange’, ‘p’, ‘e’, ‘ a’ , ‘ r’ ]
This example adds all elements of a list to the another list:
>>> odd = [1, 3, 5, 7]
>>> odd.extend ( [ 9 , 11 , 13 ] )
>>> print(odd)
[1, 3, 5, 7, 9, 11, 13]

  • One common pattern is to start a list[ ] , then use append ( ) or extend ( ) to add elements to it.

Let’s Try

Find and write the output of the following Python codes:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x.extend(y)
>>> print(x)
>>> t1 = [ ‘ a ‘ , ‘ b ‘ , ‘ c ‘ ]
>>> t2 = [ ‘ d ‘ , ‘ e ‘ ]
>>> t1.extend (t2)
>>> print ( t1 )

insert( )

You have learned that you can put an element to the end of a list by using the method “append”. To work efficiently with a list, you need also a way to add elements to arbitrary positions inside of a list. This can be done with the insert( ) method. It Inserts an item at a specified position and moves the remaining items to the right. The syntax is as follows: list.insert(<position, element)
Note: Position mentioned should be within the range of List
This example inserts an item at the beginning of a list:
>>> items
[111, 222, 333, 444]
>>> items.insert(0, 1)
>>> items
[1, 111, 222, 333, 444]
This example inserts a string in the middle of the list:
>>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, ‘four’)
>>> numbers
[1, 2, 3, ‘four’, 5, 6, 7]

  • insert ( ) method inserts the element/item at the given index, shifting elements to the right.

Let’s Try

Find and write the output of the following Python codes:

a = [ ” green ” , ” blue ” ]
print ( a )
a . insert ( 0 , ” red ” )
print ( a )
a . insert ( 2 , ” yellow ” )
print ( a )
>>> a = [2, 1, 3, 4]

#inserts element 5 at index 3
>>> a.insert (3,5)
>>> a

>>> a = [1, 5, 3, 4]
>>> a.insert(2,7)
>>> a

Example
Demo of append( ), insert( ) and extend( ) methods

# Demo of append(), insert() and extend() methods
colours = [‘Red’, ‘Orange’, ‘Green’]
print(colours) # print original list# Adding items using Python append() method
colours.append(‘Black’)
print(colours)# inserting items using Python insert() method
colours.insert(2, ‘Yellow’)
print(colours)# Extending List using Python extend() method
colours_new = [‘Blue’,’Pink’]
colours.extend(colours_new)
print(colours)RUN
>>>
[‘Red’ , ‘Orange’, ‘Green’]
[‘ Red’ , ‘Orange’, ‘Green’, ‘Black’]
[‘Red’, ‘0range’, ‘Yellow’, ‘Green’, ‘Black’]
[‘Red’ , ‘Orange’, ‘Yellow’, ‘Green’, ‘Black’,
>>>

pop( )

To delete one or more elements, i.e., remove an element, many built in functions can be used, such as pop(), remove( ) and keywords such as del. The pop() removes the item at the given position in the list and returns it. If no index is specified, pop() removes and returns “rightmost”, i.e., the last item in the list. So, you can push items onto the right end of a list and pop items off the right end of a list with append() and pop() respectively. This enables us to use the list as a stack-like data structure. Its syntax is the list.pop([index] )

Note Index is not a necessary parameter, if not mentioned takes the last index. If the optional <index> parameter is specified, the item at that index is removed and returned. <index> may be negative. <Index> defaults to -1, so list.pop(-l) is equivalent to list.pop ( ). The method ‘pop’ raises an IndexError exception if the list is empty or the index is out of range.

# Example 1: No index specified
a = [“red”, “blue”, “green”]
print(a)
a.pop( )
print(a)
>>>
[‘red’, ‘blue’, ‘green’]
[‘red’, ‘blue’ ]
>>>
# Example 2: Index specified
a = [“red”, “blue”, “green”]
print(a)
a.pop(1)
print(a)
a.pop(-2)

print ( a )
>>>
[‘red’, ‘blue’, ‘green’]
[‘red’, ‘green’]
[‘green’]
>>>
# Example 3: No index specified
>>> items = [111, 222, 333, 444, ]
>>> items
[111, 222, 333, 444]
>>> items.append(555)
>>> items
[111, 222, 333, 444, 555]
>>> items.pop ( )
555
>>> items
[111, 222, 333, 444]
>>> a = [11, 22, 33, 44, ]
>>> b = a.pop ( )
>>> a
[11, 22, 33]
>>> b
44
>>> b = a.pop ( )
>>> a
[11, 22]
>>> b
33

>>> x = [1, 2, 3]
>>> x.pop ( )
3
>>> x
[1, 2]
>>> x.pop(O)
1
>>> X
[2]

Note that when calling pop() without any arguments, the last member of the list is removed from the list and returned.

  • The pop( ) method is the only list method that both modify the list and returns a value (other than None).

Using pop( ), you can implement a common data structure called a stack. A stack like this works just like a stack of plates. You can put plates on top, and you can remove plates from the top. The last one you put into the stack is the first one to be removed. (This principle is called Last-In, First-Out, or LIFO).

  • The pop( ) method removes and returns an element at the given index.

Let’s Try

Find and write the output of the following Python codes:

>>> fruits = [“Apple”, “Banana”, “Mango”, “Pears”]
>>> fruits.pop(0) # first item
‘Apple’
>>> fruits
[“Banana”, “Mango”, “Pears”]
>>> fruits.pop(1)
‘Mango’
>>> fruits
[‘Banana’, ‘Pears’]

remove( )

The remove( ) method is used to remove the first occurrence of a value. If you know the List item or the value inside the List then, you can use the remove( ) method to remove the list item. The syntax is:
list.remove(element)
Element to be deleted is mentioned using list name and element.
>>> x = [‘to’, ‘be’, ‘or’, ‘not’, ‘to’, ‘be’ ]
>>> x.remove(‘be’)
>>> x
[‘to’, ‘or’, ‘not’, ‘to’, ‘be’]
Note that you have two ‘be’ items in this list but the remove( ) method removed only one item. This is because the remove ( ) method will only remove the first instance of the item and ignores the remaining.
>>> x.remove(‘bee’) # Removing Non Exis-ting Item from List
Traceback (most recent call last) :
File “<pyshell#3>”, line 1, in <module> x.remove(‘bee’)
NameError: name ‘bee’s not defined As you can see, you cannot remove something (in this case, the string ‘bee’) if it is not there in the list. That’s why it is throwing an error.

  • The pop( ) method removes and returns an element with a specified index or the last element if the index number is not given. The remove ( ) method removes a particular item from a list.

Let’s Try

Find and write the output of the following Python codes:

>>> a= [ 2 , 1 ,3 , 5 , 2 , 4 ]
>>> a . remove ( 2 )
>>> a
# Removing Blue Item from Colours List
Colours = [‘Red’, ‘Blue’, ‘Green’ ‘Pink’]
Colours.remove(‘Blue’)
print(Colours)

del statement

The del statement allows you to remove specific items from the list or to remove all items identified by a slice. To delete a single element from a Python list, use its index and use the slicing operator to delete a slice. The syntax is:
del list[i]
del ist [i:j]
>>> num = [‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’]
>>> del num [3] # Deleting a single element
>>> num
[‘one’, ‘two’, ‘three’, ‘five’, ‘six’] You can delete multiple elements out of the middle of a list by assigning the appropriate slice to an empty list. You can also use the del statement with the same slice:
>>> colours = [‘red’, ‘blue’, ‘green’, ‘orange’, ‘pink’, ‘black’]
>>> colours[1:5] = [ ]
>>> colours
[‘red’, ‘black’]
>>> colours = [‘red’, ‘blue’, ‘green’, ‘orange’, ‘pink’, ‘black’]
>>> del colours[1:5] # Deleting a few elements
>>> colours
[‘red’, ‘black’]
Use the del statement/keyword to delete the entire Python list.
>>> del colors # Deleting the entire Python list

  • The del statement and the pop( ) method do somewhat the same thing, except that pop returns the removed item.

Let’s Try

Find and write the output of the following Python codes:

List = [ 0 , 1 , 2 , 3 , 4 ]
print (List)
del List [ 0 ]
print ( List )
del List [ 3 ]
print (List)
fruits = [ ‘ Apple ‘ , ‘ Mango ‘ , ‘ Grape ‘ , ‘ Banana ‘ ]
del fruits [ 3 ]
print ( fruits )

reverse( )
The reverse( ) method reverses the order of items/elements in the list. It’s syntax is:
list.reverse( )
>>> x = [1 , 2 , 3]
>>> x . reverse ( )
>>> x
[3 , 2 , 1]
a1 = [“bear”, “lion”, “tiger”, “ele-phant” ]
a1.reverse ( )
print(a1)
[‘elephant’, ‘tiger’, ‘lion’, ‘bear’]

Let’s Try

Find and write the output of the following Python codes:

a = [ 3 , 7 , 5 , 2 , 6 , 1 ]
a . reverse( )
print ( a)
a1 = [ ” bee ” , ” wasp ” , ” butterfly “]
a1 . reverse ( )
print ( a1 )

sort( )

The sort( ) method is used to sort the list in place. Sorting ‘in place’ means changing the original list so its ele¬ments are in sorted order, rather than simply returning a sorted copy of the list. It does not create a new list. Its syntax is list.sort()
For example,
>>> x = [4 , 6 , 2 , 1 , 7 , 9]
>>> x.sort ( )
>>> x
[1 , 2 , 4 , 6 , 7 , 9]
The confusion usually occurs when users want a sorted copy of a list while leaving the original alone.
>>> x = [4, 6, 2, 1, 7, 9]
>>> y = x.sort ( )
# Don’t do this!
>>> print(y)
None
Since sort ( ) modifies x but returns nothing, you end up with the sorted x and the y containing None. One correct way of doing this would be to first bind y to a copy of x, and then sort y, as shown below:
>>> X = [ 4 , 6 , 2 , 1 , 7 , 9 ]
>>> y = x[ : ]
>>> y . sort( )
>>> X
[ 4 , 6 , 2 , 1 , 7 , 9 ]
>>> y
[ 1 , 2 , 4 , 6 , 7 , 9 ]
x[:] is a slice containing all the elements of x, effectively a copy of the entire list.

If the Python list members are strings, it sorts them according to their ASCII values.
>>> L1 = [‘red’, ‘Blue’, ‘Green’, ‘Red’, ‘pink’]
>>> L1.sort ( )
>>> print(L1)
[‘Blue’, ‘Green’, ‘Red’, ‘pink’, ‘red’]
>>> sorted([‘hello’,’HELLO’,’Hello’])
[‘HELLO’, ‘Hello’, ‘hello’]
>>>
The sort( ) method sorts the elements in ascending order. With the reverse parameter set to True, the list is sorted in a descending order.
list.sort(reverse=True)
>>> names=[‘Vivek’, ‘Mohan’, ‘Swati’, ‘Krishna’]
>>> names.sort(reverse=True)
>>> print(names)
[‘Vivek’, ‘Swati’, ‘Mohan’, ‘Krishna’]
The built-in function sorted returns a new sorted list without modifying the source list. In other words, it returns a sorted version of the list, but does not change the original one. It’s syntax is :
list.sorted ( )
>>> a = [4 , 3 , 5 , 9 , 2 ]
>>> sorted(a)
[2 , 3 , 4 , 5 , 9]
>>> a
[ 4 , 3 , 5 , 9 , 2 ]

The behavior of the sort method and sorted function is exactly the same except that sorted returns a new list instead of modifying the given list.

Example
Program to sort list in ascending and descending order using sort ( ) method.

# Program to sort list in ascending and descending order using sort ( ) method.
n = [ 6 , 7 , 2 , 1 , 2 , 9 , 5 , 6 ]print ( ” original List ” )
print ( n )print ( ” sorted List in ascending order ” )
n . sort ( )
print ( n )print ( ” sorted List in descending order ” )
n . sort (reverse = True )
print ( n )RUN
>>>
Original List
[6, 7, 2, 1, 2, 9, 5, 6]
Sorted List in ascending order
[ 1 , 2 , 2 , 5 , 6 , 6 , 7 , 9 ]
Sorted List in descending order
[ 9 , 7 , 6 , 6 , 5 , 2 , 2 , 1 ]
>>>

Let’s Try

Find and write the output of the following Python codes:

>>> a = [ 3 , 6 , 5 , 2 , 4 , 1 ]
>>> a . sort ( reverse = True )
>>> print ( a )
>>> t = [ ‘ d ‘ , ‘ c ‘ , ‘ e ‘ , ‘ b ‘ , ‘ a ‘ ]
>>> t.sort ( )
>>> print ( t )
  • sort ( ) sorts items in a list in ascending order.

clear( )

When you are done with a list, you can remove all values contained in it by using the list.clear() method. clear() removes all items/elements from the list. It is equivalent to del a[:].
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.clear ( )
[ ]
Note that after executing this method, it returns an empty list.

  • You can also use the clear ( ) method to empty a list.

Let’s Try

Find and write the output of the following Python codes:

>>> a = [ 3 , 6 , 5 , 2 , 4 , 1 ]
>>> a . clear ( )
>>> print ( a )
>>> t = [ ‘ d ‘ , ‘ c ‘ , ‘ e ‘ , ‘ b ‘ , ‘ a ‘ ]
>>> t . clear ( )
>>> print ( t )

max( ) and min( )

max( ) returns the largest item in an iterable (Eg, list) or the largest of two or more arguments. If more than one item shares the maximum value, only the first one encountered is returned. min( ) returns the smallest item in an iterable (Eg, list) or the smallest of two or more arguments.
>>> x = [4, 6, 2, 1, 7, 9]
>>> max(x)
9
>>> min(x)
1
a = [11, 12, 13, 14, 15]
b = [11, 12, 13, 14]
print(max(a, b))
print(min(a,b))
>>>
[11, 12, 13, 14,
[11, 12, 13, 14]
>>>

Example
Use of max ( ) & min ( )

# Use of max() & min()
names = [“Meera”,”Aman”, “Sangeeta”, “Preeti”, “upma” , ” Nikitha” ]
print(“Original List”)
print(names)
print(“Maximum “, max(names))
print(“Minimum “, min(names))RUN
>>>
Original List
[‘Meera’, ‘Aman’, ‘Sangeeta’, ‘Preeti’, ‘Upma’, ‘ Nikitha’ ]
Maximum Upma
Minimum Aman
>>>

Example
Program to find maximum and minimum in list

# Program to find maximum and minimum in list
n = [6, 7, 2, 1, 2, 9, 5, 6]
print(“Original List”)
print(n)
print(“\nMaximum “, max(n))print(“\nMinimum “, min(n))RUN
>>>
Original List
[6, 7, 2, 1, 2, 9, 5, 6]
Maximum 9
Minimum 1
>>>
  • max( ) returns the largest item in the list where as min( ) returns the smallest item in the list.

Let’s Try

Find the outputs for the following:

y = [10, 42, 72, 16, 27]
m = max(y)
p = y.index(m)
print(m, p)
1st = [0, 1, 2, 3, ‘four’, 0x101]
print( len(1st))
Num List = [ 4 , 13 , 22 , 29 , 30 , 44 , 52 ]
Num List.sort( )
print(“Sorted list is “,Num_List)
print(“Mid value is “,
Num_List[int(len(Num_List)/2)])
TXT = [“20″,”50″,”30″,”40”]
CNT = 3
TOTAL = 0
for C in [7,5,4,6]:
T = TXT[CNT]
TOTAL = float (T) + C
print(TOTAL)
CNT-=1
Name = [ ” Amar ” ,” Shveta ” , ” parag ” ]
for i in name
if i [ 0 ] == ‘ s ‘
print ( i )

Leave a Reply

Your email address will not be published. Required fields are marked *