Now, we will finally remove that inner list. Type this in Python to get rid of it at last:
family.remove(['Jason', 'Jake'])
print(family)
['Jack', 'Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', 'Grandpa', 'Grandma', 'Alison']
We finally got the list gone. But, removing an item like that does not give a good example for someone who doesn't know this function yet. Let's take away another item in the list.
family.remove('Jack')
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', 'Grandpa', 'Grandma', 'Alison']
Sorry, I forgot Louis! You might as well remove him. Anyway, remove takes away single items in the list. But, there's a slightly faster way to get rid of an item. This is the del function. Try this:
del family[5]
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Grandpa', 'Grandma', 'Alison']
Del took away the 5th index in the list, which was "Betty." Instead of saying the entire string, you can just use the index it is. But, what about pop()?
Pop() takes the last item off of the list and gives it back to you, so you can assign it to a different variable, like so:
ex1=family.pop()
print(ex1)
Alison
"Alison" was at the end of the list, and pop() took that item off and put it in ex1. But, what about the list?
print(family)
['Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Grandpa', 'Grandma']
Pop() didn't give us a copy of the last index, it actually tore it off of family and gave it to ex1. But, what if we want to pop an item in the middle of the list? This is how we do that:
ex2=family.pop(4)
print(ex2)
Willy
That's the reason the parenthesis (()) are there. If you don't put a number in them, Python knows just to take the last item off and give it to the assigned variable. However, the number in the parenthesis must be an index in the list, or you will get an error. You can try it yourself if you don't believe me.
So, you learned about how to delete items in a list. Things will get even more complicated later on during lists, so I will go back to the easier functions so you don't get confused.
No comments:
Post a Comment