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:
Because the 4th index is the 5th element, as the index numbers start from
This also requires the index number.
>>> del myList
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
while loop for converting list to string.
mylist = ['butter', 'jam', 'curd'] myStr = ', '.join(mylist) print (myStr);
butter, jam, curd
If you have a list of
int values, then
mylist = [1, 11, 111] myStr = str(mylist).strip('') print (myStr);
1, 11, 11
If we have a list of
mylist = [1, 11, 111] myStr = ''.join(str(e) for e in mylist) print (myStr)
1, 11, 11
More functions for Lists
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,
As obvious by the name, it is used to reverse the order of the elements in the list.
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.
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?
This will first sort the elements in ascending order and then we have used the
reverse() function to reverse the list.