Deleting an element from a List

It may happen, that you might have to delete some elements from your list. Below we have listed some methods to do the same:


pop( ) function:

This method requires the index number of the element that you want to delete. For example, if you want to delete the 5th element of the list, then just do it like:

>>> myList.pop(4)

Live Example →

Because the 4th index is the 5th element, as the index numbers start from 0.


del keyword:

This also requires the index number.

>>> del myList[4]

This will delete the 5th element of the list. We can combine this with slicing to delete sequence of elements together, like if we want to delete all elements from index 3 to 6, then:

>>> del myList[3:7]

This will remove all elements from index 3 to 6.


remove( ) function:

This function, instead of index number, requires the value that has to be deleted. For example,

>>> myList = ['Apple', 'Orange', 'Apple', 'Guava']
>>> myList.remove('Apple')

This will remove the first 'Apple' element from the list. Other elements with value 'Apple' won't be deleted. i.e., our list will be:

>>> print myList

['Orange', 'Apple', 'Guava']


Convert a List to String

If you want to convert your list into a string to print it as output, you can do it easily.

Without using any loop

Here is the code, if you do not want to use for or while loop for coverting list to string.

mylist = ['butter', 'jam', 'curd']
myStr = ', '.join(mylist)
print myStr

butter, jam, curd

Live Example →

If you have a list of int values, then

mylist = [1, 11, 111]
myStr = str(mylist).strip('[]')
print myStr

1, 11, 11


Using for loop

If we have a list of int values,

mylist = [1, 11, 111]
myStr = ''.join(str(e) for e in mylist)
print myStr

1, 11, 11


More functions for Lists

1. insert(int, item)

This function is used to insert values, anywhere in the list. The first argument of the list takes the index where the items will be inserted and second is the value that has to be inserted. For example,

>>> myList = ['Python', 'C++', 'Java', 'Ruby', 'Perl']
>>> myList.insert(1, 'JavaScript')
>>> print myList

['Python', 'JavaScript', 'C++', 'Java', 'Ruby', 'Perl']

Live Example →

Notice how the value 'JavaScript' got inserted at index the 1.


2. reverse()

As obvious by the name, it is used to reverse the order of the elements in the list.

>>> myList.reverse()

Live Example →


3. sort()

One of the most important functions in real life applications is sort(). Sorting arranges all the elements of the List in ascending or descending order.

>>> myList.sort()

Live Example →

If the list consists of numbers then this will make the sequence in ascending order, if the list consists of strings then the elements will be sorted in lexicographic ascending order.

What if you want to sort in descending order?

>>> myList.sort().reverse()

This will first sort the elements in ascending order and then we have used the reverse() function to reverse the list.