Python – More List Methods and Recipes

Remove items from a List and more.

“Happiness is a perfume you cannot pour on others without getting some on yourself.” ― Ralph Waldo Emerson

1. Introduction

In a previous article, we covered some python list methods related to adding items. Let us now continue the review of more list methods.

2. Removing Items

There are several ways of removing items from a python listremove(), the del operator, pop() and assignment.

2.1. remove()

The method remove() finds the specified value in the list and removes it.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a.remove(4)
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'fish', 'snake']

Note carefully that the item is not specified by index, but by value.

Here is another example.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a.remove('fish')
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 4, 'snake']

What happens when you try to remove an item which does not exist in the list? A ValueError:

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
try: a.remove('squirrel')
except Exception as x:
    print '3.', x
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
3. list.remove(x): x not in list
2. ['cat', 'dog', 'fish', 4, 'snake']

2.2. del

What if you want to remove items from the list by index? The operator del can remove an item specified with the index.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[4]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'fish', 4]

It is an error to specify an invalid index: you get an IndexError in your face.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
try: del a[8]
except Exception as x:
    print '2.', x
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. list assignment index out of range

Of course, you can specify a negative index to refer to an element from the end of the list, with the last element being at -1. Again, the index must be valid i.e. must not be less than -len(a).

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[-1]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'fish', 4]

The del operator can also delete ranges with the usual slice syntax. The following deletes all elements from second on.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[1:]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat']

Not only opened ended ranges, but closed ones too. (The second element in the range is an index, not a length.)

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[2:4]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'snake']

When the second index is less than 0, it refers to items from the end.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[:-2]
print '2.', a
# print
1. ['cat', 'dog', 'fish', 4, 'snake']
2. [4, 'snake']

Either of the indices can be negative.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[1:-2]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 4, 'snake']

The second index can be less than the first index. In this case, no exception is raised; the condition is silently ignored.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
del a[-2:-4]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'fish', 4, 'snake']

2.3. pop()

The method pop() removes and returns the last item from the list.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
print '2.', a.pop()
print '3.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. snake
3. ['cat', 'dog', 'fish', 4]

With an argument, pop(i) removes and returns the item at that index.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
print '2.', a.pop(1)
print '3.', a
#prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. dog
3. ['cat', 'fish', 4, 'snake']

With a negative argument, it removes that item starting from the end.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
print '2.', a.pop(-2)
print '3.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. 4
3. ['cat', 'dog', 'fish', 'snake']

When the index specified is out of range, the method raises an IndexError.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
try: print a.pop(8)
except Exception as x:
    print '2.', x
print '3.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. pop index out of range
3. ['cat', 'dog', 'fish', 4, 'snake']

2.4. Assignment

Python supports a slice assignment syntax which can also be used to remove items from the list. In this manner, it works just like del above.

Here is how it is done. Select a slice on left hand side and assign an empty list to it.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a[1:2] = []
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'fish', 4, 'snake']

Remove multiple items too. And yes, you can use negative indices too.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a[2:-1] = []
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'snake']

Indexes can fall outside of valid ranges.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a[8:1] = []
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'dog', 'fish', 4, 'snake']

However, the additional advantage of using this method over del is that you can replace items in the list by assigning on the right.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a[0:2] = ['joe']
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['joe', 'fish', 4, 'snake']

A single item can be replaced by multiple items.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
a[1:2] = ['joe', 'jack', 2.5]
print '2.', a
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. ['cat', 'joe', 'jack', 2.5, 'fish', 4, 'snake']

3. Find an Item Using index()

This method allows you to search through a list for an item and return the index.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
print '2.', a.index('dog')
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
2. 1

A ValueError exception is raised when the item is not found.

a = ['cat', 'dog', 'fish', 4, 'snake']
print '1.', a
print '2.', a.index('man')
# prints
1. ['cat', 'dog', 'fish', 4, 'snake']
ValueError: 'man' is not in list

4. Finding All Indices

The index() method returns the index of the first item only. To find all indices, use the following.

a = ['cat', 'dog', 'fish', 4, 'snake', 'dog']
print '1.', a
print '2.', [i for i, j in enumerate(a) if j == 'dog']
# prints
1. ['cat', 'dog', 'fish', 4, 'snake', 'dog']
2. [1, 5]

You can use zip() with itertools.count() also for the purpose. (Check out this article on itertools.)

print '3.', [i for i, j in zip(itertools.count(), a) if j == 'dog']
3. [1, 5]

5. Count Occurences of Search Term

Use the method count() to find how many instances of your search term are present.

a = ['cat', 'dog', 'fish', 4, 'snake', 4]
print '1.', a
print '2.', a.count(4)
# prints
1. ['cat', 'dog', 'fish', 4, 'snake', 4]
2. 2

Not finding any items in the list is not an exception – the return value is 0.

a = ['cat', 'dog', 'fish', 4, 'snake', 4]
print '1.', a
print '2.', a.count('squirrel')
# prints
1. ['cat', 'dog', 'fish', 4, 'snake', 4]
2. 0

Conclusion

In this article, we have learnt about some more list methods. Methods for remove include remove(), del, pop() and assigning when using the slice operator. Finding an item in a list is done with index() which returns the index of the first item.

Leave a Reply

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