So... we made a list of names called, by the way, names (this is the name of the list, the label, the object is the list, while names is just the label, or name, of that object).
names = ["John","Carl","Mary","Sean","Sally"]
What if I want to delete Carl?
If I know that Carl index is 1, as it is, I can write this code:
>>> del names[1]
But, what if I don't know the index of Carl? Well, we can find the index of it and then delete it. Let's make that Python does all the work.
>>> del names[names.index("Carl")]
If you want you could have done, taking it easier, this way
>>> indexOfCarl = names.index("Carl")
>>> del names[indexOfCarl]
It's a bit too long, but the result is the same. In fact:
>>> names
["John","Mary","Sean","Sally"]
There in not the name of Carl in the list any more.
>>> names.pop()
'Sally'
The last one is out (last in first out).
>>> names.pop(0)
"John"
The first one is out.
>>>names
['Sean', 'Sally']
Next time we will be looking at list comprehension.
names = ["John","Carl","Mary","Sean","Sally"]
What if I want to delete Carl?
If I know that Carl index is 1, as it is, I can write this code:
>>> del names[1]
But, what if I don't know the index of Carl? Well, we can find the index of it and then delete it. Let's make that Python does all the work.
>>> del names[names.index("Carl")]
If you want you could have done, taking it easier, this way
>>> indexOfCarl = names.index("Carl")
>>> del names[indexOfCarl]
It's a bit too long, but the result is the same. In fact:
>>> names
["John","Mary","Sean","Sally"]
There in not the name of Carl in the list any more.
Let's pop
We can also do:>>> names.pop()
'Sally'
The last one is out (last in first out).
>>> names.pop(0)
"John"
The first one is out.
>>>names
['Sean', 'Sally']
Next time we will be looking at list comprehension.
Comments
Post a Comment