In this lesson, you’ll learn about the additional built-in methods that, unlike the ones in the previous lesson, have return values.
.pop(<index=-1>)
removes an element from the list at the specified index. The item that was removed is returned. The default is to remove the last item in the list <index=-1>
if no index is specified:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.pop()
'lobster'
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham']
>>> b = a.pop()
>>> b
'ham'
>>> a
['spam', 'egg', 'bacon', 'tomato']
>>> a.pop(1)
'egg'
>>> a
['spam', 'bacon', 'tomato']
>>> a.pop(-2)
'bacon'
>>> a
['spam', 'tomato']
.index(<obj>[,<start>[, <end>]])
returns the first index of the value <obj>
in the list. Optional start and end indexes can be used. It raises an exception if the value <obj>
is not present:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a.index('tomato')
3
>>> a[3]
'tomato'
>>> a.index('egg', 0, 4)
1
>>> a.index('egg', 2, 5)
Traceback (most recent call last):
File "<input>", line 1, in <module>
a.index('egg', 2, 5)
ValueError: 'egg' is not in list
kiran on July 24, 2020
Hi can you update this airtical List and Tuples with following methods…?
mylist.index(<obj>[, <start>[, <end>]]) mylist.count(<obj>) mylist.copy() - returns a shallow copy
if possible shallow vs deep copy too. Thank you.