List indexing and slicing operations

The following operations use the indexing and slicing features of lists:

• To return the index number of a list item, use the index() method. If the item isn't in the list, it raises a vaiueError.

This example returns the index number of the second item in the list:

>>> mylist = [1, 'two', 3] >>> mylist.index('two') 1

• To remove from a list the item(s) corresponding to the given index number or slice, use the keyword del.

This example deletes two items.

>>> mylist2 = ['busy signal', 'fast busy signal', 'no such number', 'at the tone, the time will be']

• To insert an item before a particular index number, use the insert() method.

To remove and return an item at a particular index number, use the pop() method. The default index number for pop() is the last item in the list. This example removes and returns the item 'baked beans' in the list breakfast: >>> breakfast = ['spam', 'spam', 'spam', 'baked beans', 'spam', 'spam']

>>> breakfast.pop(3) 'baked beans' >>> breakfast

The following code uses a while loop to return and delete all the list elements one at a time:

Was this article helpful?

0 0

Post a comment