Blog

Python List Methods

  • (4.0)
  • | 1679 Ratings

Introduction


List is one of the four collection data types in the Python programming language which is ordered and also changeable. It allows duplicate members too. Lists need not always be homogeneous thus making it one of the most powerful tools in Python. A single list may contain various datatypes like Integers, Strings, as well as Objects. Lists are also helpful in implementing stacks and queues. Since they are mutable, they can be changed even after their creation.

Python has some list methods which are built-in that you can use to perform frequently occurring tasks (related to list) with ease. For example, if you would like to add element to a list, you can make use of append() method. By the end of this article, you’ll be familiar with many functions used on Python lists.

In this article, we will discuss the following Python List Methods, making sure you clearly understand the meaning, syntax, parameters used, and solidify your understanding with an example. The List Methods explored here are as follows.


  • Python List append()
  • Python List extend()
  • Python List insert()
  • Python List remove()
  • Python List index()
  • Python List count()
  • Python List pop()
  • Python List reverse()
  • Python List sort()
  • Python List copy()
  • Python List clear()

Python List Methods


Method Description
Python List append() Add Single Element to The List
Python List extend() Add Elements of a List to Another List
Python List insert() Inserts Element to The List
Python List remove() Removes Element from the List
Python List index() returns smallest index of element in list
Python List count() returns occurrences of element in a list
Python List pop() Removes Element at Given Index
Python List reverse() Reverses a List
Python List sort() sorts elements of a list
Python List copy() Returns Shallow Copy of a List
Python List clear() Removes all Items from the List
Python any() Checks if any Element of an Iterable is True
Python all() returns true when all elements in iterable is true
Python ascii() Returns String Containing Printable Representation
Python bool() Converts a Value to Boolean
Python enumerate() Returns an Enumerate Object
Python filter() constructs iterator from elements which are true
Python iter() returns iterator for an object
Python list() Function creates list in Python
Python len() Returns Length of an Object
Python max() returns largest element
Python min() returns smallest element
Python map() Applies Function and Returns a List
Python reversed() returns reversed iterator of a sequence
Python slice() creates a slice object specified by range()
Python sorted() returns sorted list from a given iterable
Python sum() Add items of an Iterable
Python zip() Returns an Iterator of Tuples

Let us now see one after the other the popular python list methods. 


Python List append()


The append() method makes an addition of a single item to the existing list. Rather than returning a new list; it actually modifies the original list. Python List append() can be considered useful in appending a passed obj into the existing list or appending an element to the end of the list.


python list append


Image source: https://www.afternerd.com/blog/append-vs-extend/
 

The syntax of append() method is as follows:


list.append(item)

append() Parameters


The append() method takes a single item as an input and then adds it to the end of the list.
The item can be anything like another list, strings, numbers, dictionary etc.

Return Value from append()
As already mentioned, the append() method only makes modifications to the original list. It doesn't return any value.

Let us see two examples. First one is appending an element to a list and the second is explaining addition of a list to an existing list. 


Adding Element to a List

# animal list
animal = ['cat', 'dog', 'rabbit']

# an element is added
animal.append('guinea pig')

#Updated Animal List
print('Updated animal list: ', animal)

When you run the program, the output generated will be:

Updated animal list:  ['cat', 'dog', 'rabbit', 'guinea pig']


Frequently Asked Python Interview Questions & Answers


Adding List to a List?

# animal list
animal = ['cat', 'dog', 'rabbit']

# another list of wild animals
wild_animal = ['tiger', 'fox']

# adding wild_animal list to animal list
animal.append(wild_animal)

#Updated List
print('Updated animal list: ', animal)

?When you run the program, the output generated will be:

Updated animal list:  ['cat', 'dog', 'rabbit', ['tiger', 'fox']]

It's important to take a note that, a single item (wild_animal list) is added to the animal list in the above program. If you require to add items of a list to another list (rather than the list itself), we use the extend() method.


Python List extend()


The Python extend() function extends the list by adding all items of a list (which are passed as an argument) to the end.

The syntax of extend() method is as follows:

list1.extend(list2)

Here, to the end of list1, the elements of list2 are added 

extend() Parameters

As already mentioned, the extend() method takes only a single argument (which is a list) and then adds it to the end.

If you require to make an addition of elements of other native datatypes (like tuple and set) to the list, you can use:

# add elements of a tuple to list
list.extend(list(tuple_type))

or even like this
list.extend(tuple_type)    

Return Value from extend()

Similar to the python append() function, the extend() method only makes modifications to the original list. It does not return any value.

Let us see an example making use of the extend() Method

# language list
language = ['French', 'English', 'German']

# another list of language
language1 = ['Spanish', 'Portuguese']

language.extend(language1)

# Extended List
print('Language List: ', language)
When you run the program, the output generated will be:

Language List:  ['French', 'English', 'German', 'Spanish', 'Portuguese']


Difference between append() and extend()


The major difference is that append adds an element to the list, whereas extend concatenates the first list with another list (or another iterable, need not be a list).


Python List insert()


The Python insert() method helps in inserting the element to the list at the given index.

The syntax of the insert() is as follows:
list.insert(index, element)

insert() Parameters:
The insert() function takes in only two parameters:

index - it is the position where the element needs to be inserted
element - this is the element which needs to be inserted in the list

Return Value from insert()

The insert() method just like append() and extend(), only inserts the element to the list. It doesn't return any value.

Let us go through an example of Inserting an Element to List

# vowel list
vowel = ['a', 'e', 'i', 'u']

# inserting element to list at 4th position
vowel.insert(3, 'o')

print('Updated List: ', vowel)

When you run the program, the output generated will be:

Updated List:  ['a', 'e', 'i', 'o', 'u']

It is important to take note that indexes in Python starts from 0 not 1. In case you want to insert element in 4th place, you have to pass 3 as an index. Similarly, if you want to insert element in 9thnd place, you have to use 8 as an index.


 
Python List remove()


The remove() method is used for searching for the given element in the list and it then removes the first matching element.
The syntax of remove() method is as follows:
list.remove(element)

remove() Parameters are as follows:
The remove() method takes only a single element as an argument which is then removed from the list.
In case the element(argument) which has been passed to the remove() method doesn't exist, valueError exception is thrown.

Return Value from remove()

The remove() method only does the job of removing the given element from the list. It doesn't return any value.

Let us consider an example of Removing an Element from the List

# animal list
animal = ['cat', 'dog', 'rabbit', 'guinea pig']

# 'rabbit' element is removed
animal.remove('rabbit')

#Updated Animal List
print('Updated animal list: ', animal)

When you run the program, the output generated will be:

Updated animal list:  ['cat', 'dog', 'guinea pig']

The remove() method only removes the element which has been passed as an argument. But in case you need to delete elements based on index (like seventh element or first element), you need to use either pop() method or del operator.
This function finds its use for following native datatypes:
Python Set remove()


Python List index()


The index() method makes a search for an element in the list and then returns its index. Simply put, index() method finds the given element in a list and then returns its position but in case an element is present more than once, the smallest/first position is returned first. 

The syntax of index() method is as follows:

list.index(element)

index() Parameters

The index method takes in only a single argument:
element - element that is to be searched.

Return value from index()

The index() method as expected returns the index of the element in the list.

In case it isn't found, a ValueError exception is raised indicating the element not in the list.

Let us take a look at an example which finds position of element in the list.

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# element 'e' is searched
index = vowels.index('e')

# index of 'e' is printed
print('The index of e:', index)

# element 'i' is searched
index = vowels.index('i')

# only the first index of the element is printed
print('The index of i:', index)
When you run the program, the output generated will be:

The index of e: 1
The index of i: 2

This function also finds its use for following native datatypes:

Python Tuple index()
Python String index()


Python List count()


The count() method is used to return the number of occurrences of an element in a list. In easier terms, count() method first counts how many times an element has occurred in the list and then returns it.

The syntax of count() method is:
list.count(element)

count() Parameters are as follows:
The count() method takes only a single argument:
element - element whose count is to be found.

Return value from count()
The count() method returns the number of occurrences of an element in a list.

Let us consider an example where we count the occurrence of an element in the list

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']

# count element 'i'
count = vowels.count('i')

# print count
print('The count of i is:', count)

# count element 'p'
count = vowels.count('p')

# print count

When you run the program, the output generated will be:

The count of i is: 2
The count of p is: 0
This function finds its use for the following native datatypes:
Python Tuple count()


Python List pop()


The pop() method first removes an element and then returns it at the given index (passed as an argument) from the list.
The syntax of pop() method is as follows:
list.pop(index)

pop() parameter are as follows:
The pop() method takes only a single argument (index) and by this removes the element present at that index from the list.
Whenever the index passed to the pop() method is not in the range, an exception IndexError: pop index out of range is thrown.
The parameter which is passed to the pop() method is optional. If in case no parameter is passed, the default index -1 is passed as an argument which then returns the last element. 

Return Value from pop()
The pop() method has a return value It returns the element present at the given index. Apart from this, the pop() method also removes the element at the given index and updates the list.

Let us consider an example which prints an Element Present at the Given Index from the List

# programming language list
language = ['Python', 'Java', 'C++', 'French', 'C']

# Return value from pop()
# When 3 is passed
return_value = language.pop(3)
print('Return Value: ', return_value)

# Updated List
print('Updated List: ', language)

When you run the program, the output generated will be:

Return Value:  French
Updated List:  ['Python', 'Java', 'C++', 'C']

The pop() method returns and removes the element at the given index but in case if you require to remove the given element from the list, you need to use remove() method.


Python List reverse()


The reverse() method helps in reverse-sing the elements of a given list.
The syntax of reverse() method is as follows:
list.reverse()

reverse() parameter are as follows:
The reverse() function doesn't take any argument.

Return Value from reverse()
The reverse() function doesn't return any value. It's only function is to reverse the elements and update the list.

Let us see how we can reverse a List
# Operating System List
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)

# List Reverse
os.reverse()

# updated list
print('Updated List:', os)

When you run the program, the output generated will be:

Original List: ['Windows', 'macOS', 'Linux']
Updated List: ['Linux', 'macOS', 'Windows']


Python List sort()


Similar to C++ sort(), Java sort() and other languages, python also has a built in function to sort. The sort function can be utilized to sort the list in both ascending and also descending order.

The Syntax of Python sort() is as follows:

list_name.sort() – this one sorts the list ascending order
list_name.sort(reverse=True) – this one sorts the list  in descending order
list_name.sort(key=…, reverse=…) – this one sorts the list according to user’s choice

The Parameters of sort() function are: 

By default, Python sort() function doesn’t require any extra parameters. It has two optional parameters:

reverse – If it is true, the list will be sorted in descending order
key – this function that acts as a key for the sort comparison

Return value:

A sorted list is returned according to the passed parameter.


List_name.sort()


This will help in sorting the given list in ascending order. This function finds its use in sorting list of integers, floating point number, string and others.
Let us check an example which will sort a list in ascending order.

# List of Integers 
numbers = [1, 3, 4, 2] 
  # Sorting list of Integers 
numbers.sort() 
  
print(numbers) 

# List of Floating point numbers 
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] 
  
# Sorting list of Floating point numbers 
decimalnumber.sort() 

print(decimalnumber) 
  
# List of strings 
words = ["Geeks", "For", "Geeks"] 
  
# Sorting list of strings 
words.sort() 
  
print(words) 

The generated Output will be :

[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['For', 'Geeks', 'Geeks']

list_name.sort(reverse=True)

This will help in sorting the given list in descending order. Let us look at an example for the same. 

# List of Integers 
numbers = [1, 3, 4, 2] 
  
# Sorting list of Integers 
numbers.sort(reverse=True) 
  
print(numbers) 
  
# List of Floating point numbers 
decimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68] 
  
# Sorting list of Floating point numbers 
decimalnumber.sort(reverse=True) 
  
print(decimalnumber) 
  
# List of strings 
words = ["Geeks", "For", "Geeks"] 
  
# Sorting list of strings 
words.sort(reverse=True) 

print(words) 

The generated Output will be :

[4, 3, 2, 1]
[3.67, 3.28, 2.01, 2.0, 1.68]
['Geeks', 'Geeks', 'For']

Let us also look at a Python program to demonstrate sorting by user's choice.
  
# function to return the second element of the 
# two elements passed as the paramater 
def sortSecond(val): 
    return val[1]  
  
# list1 to demonstrate the use of sorting  
# using using second key  
list1 = [(1,2),(3,3),(1,1)] 
  
# sorts the array in ascending according to  
# second element 
list1.sort(key=sortSecond)  
print(list1) 
  
# sorts the array in descending according to 
# second element 
list1.sort(key=sortSecond,reverse=True) 
print(list1) 
Copy CodeRun on IDE

The generated Output will be :

[(1, 1), (1, 2), (3, 3)]
[(3, 3), (1, 2), (1, 1)]

Python List copy()
The copy() method helps in returning a shallow copy of the list.
A list can be copied using the = operator. For example:
old_list = [1, 2, 3]
?new_list = old_list

The worry with copying the list in this method is that if you will modify the new_list, the old list
Is also modified.

old_list = [1, 2, 3]
new_list = old_list

# add element to list
new_list.append('a')

print('New List:', new_list )
print('Old List:', old_list )

When you run the program, the output generated will be:

Old List: [1, 2, 3, 'a']
New List: [1, 2, 3, 'a']

However, if you require the original list without any changes when the new list is modified, you 
can use copy() method. This is called shallow copy.



python-list-copy-typesImage source: https://django.cowhite.com/blog/python-lists-shallow-and-deep-copy/


The syntax of copy() method is as follows:

new_list = list.copy()

copy() parameters:
The copy() method doesn't take any parameters.
Return Value from copy():
The copy() function only returns a list. It doesn't modify the original list.

Let us see an example of Copying a List
# mixed list
list = ['cat', 0, 6.7]

# copying a list
new_list = list.copy()

# Adding element to the new list
new_list.append('dog')

# Printing new and old list
print('Old List: ', list)
print('New List: ', new_list)
 
When you run the program, the output generated will be:
Old List: ['cat', 0, 6.7]
New List: ['cat', 0, 6.7, 'dog']
You can observe that the old list remains unchanged even after the new list is modified.

Python List clear()
The clear() method helps in removing all items from the list.

The syntax of clear() method is as follows :
list.clear()

clear() Parameters:
The clear() method doesn't take in any parameters.

Return Value from clear():
The clear() method only empties the given list but doesn't return any value.

# Defining a list
list = [{1, 2}, ('a'), ['1.1', '2.2']]

# clearing the list
list.clear()

print('List:', list)

When you run the program, the output generated will be:

List: []

Note: If you are working with Python 2 or Python 3.2 and below, you cannot use the clear() method. You can utilize the del operator instead.


Conclusion


With so much of power at your hands with the list functions of python, we expect our readers to starting experimenting with them. Apart from using the above functions, you would be benefitting a lot from making use of concepts such as Indexing, Slicing and Matrixes. Since lists are basically sequences, indexing and slicing work in a similar way for lists as they usually do for strings. 


Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Anjaneyulu Naini
About The Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, SAS, Artificial Intelligence, Oracle, Business Intelligence, Altrex etc, Connect with him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close