Now that you know enough about Python, it's about time we get back to lists.
What if we have a really long list, and we want to find an item in it? To search a list, we have to use the in function.
You probably got rid of the family list from the other articles, so let's make a different one.
numbers=['1', '2', '3', '4', '5', '6']
Let's say we don't know if the number 3 is in the list. This is where the function comes in:
if '3' in numbers:
print("3 is in the numbers.")
else:
print("3 is not in the numbers.")
You should get "3 is in the numbers." Let's try this again, but with a number that really isn't in the list.
if '10' in numbers:
print("10 is in the numbers.")
else:
print("10 is not in the numbers.")
You should get "10 is not in the numbers." The in statement basically debates if an item being in the list is true or false.
There's even a kinda faster way to do this:
'1' in numbers
This should appear:
True
But if you do a false one:
'99' in numbers
False
So if you do a quick thing like that, it just says "True" or "False."
You can even do a group of numbers at a time, like this:
'1' in numbers and '2' in numbers and '3' in numbers and '4' in numbers and '5' in numbers
True
But if 1 number is not in the list...
'1' in numbers and '2' in numbers and '7' in numbers
False
There you have it. We can even remove items we found in the list, like this:
if '6' in numbers:
numbers.remove('6')
print(numbers)
['1', '2', '3', '4', '5']
You can even remove a number if a different one is in the list.
if '1' in numbers:
numbers.remove('5')
print(numbers)
['1', '2', '3', '4']
Now that we have that covered, what if we want to find an item's index?
numbers.extend(['5', '6'])
(I had to put the numbers back in since I was running out.)
print(numbers.index('5'))
4
That is the index of the number, not the number itself (duh). You can do the same thing with index() that you can do with remove().
if '6' in numbers:
print(letters.index('6'))
5
You can also do the other thing I explained with remove(), if a certain number is in the list, then remove a different number.
Well, that's all there is to searching a list. That was a lot to cover in this article, wasn't it?
No comments:
Post a Comment