How do I check if an item from a list is in another list?

Question:

I was trying to write a simple Python 3 program and cant find answers.

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

for i in fruits:
    if fruits[i] in favoritefruits:
        print("I'm gonna buy some " + fruits[i] + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruits[i] + ", I don't like them.")
Asked By: legend

||

Answers:

As @wkl has stated, for i in fruits will iterate through all fruit names, not the index. Replacing fruits[i] with i (though a more descriptive name is better) will fix the issue:

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

for fruit in fruits:
    if fruit in favoritefruits:
        print("I'm gonna buy some " + fruit + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruit + ", I don't like them.")
Answered By: knosmos

List Indexes

In python, each element in a list has an index where the first element (foo) has an index of 0.
The value of each element’s index is simply incremented, corresponding to the amount of items in each list.

l = ['foo', 'bar', 'baz']

For example, foo has an index of 0, bar has an index of 1, and so on.

When iterating through a list using a for loop, python outputs the element.

for i in fruits
    print(i)

Enumerating a List

However, python also has an enumerate function, which tracks and increments the index at runtime.

for index, value in enumerate(l):
    print("{value} has an index of {index}")

>>> foo has an index of 0
>>> bar has an index of 1
>>> baz has an index of 2

The in keyword

You may also use the operator keyword in to determine if a list contains a given element.

For example, the syntax to deterine a string in a list, we can use the list in our previous example:

if 'foo' in l:
    print('Hooray! Our word is in the list!')

or, in your case, comparing an element from one list to an elemnt in another list:

jacks_animals = ['pig', 'horse', 'cow', 'sheep', 'rabbit', 'dog', 'chicken', 'cat']
johns_animals = ['horse', 'sheep', 'rabbit', 'dog', 'bird', 'wolf', 'kangaroo', 'fox']

for animal in jacks_animals:
    if animal in john_animals:
        print(f"Horray! Both john and jack has a {animal}")
        continue # continue sends us to the start of our loop, ignoring code after the continue statement
    print(f"Only jack has a {animal}")

Sub-scripting Using the Index

To extract an element from a list by sub-scripting it’s known index value, its index must be of type int.
In your snippet, you sub-scripted a list using type str. In python, you can yield a value like this with dict datatypes.

You can get any element in a list, without even specifying the name of the element, and only using the index.
This can be done like this:

l = ['foo', 'bar', 'baz']
print(l[0])

>>> 'foo'

Answered By: Joshua Rose

You Have Two Lists: fruits and favoritefruits

fruits = ["strawberries", "apples", "bananas", "pomegranates", "blueberries", "dragon fruits", "papayas", "pears", "oranges", "mango", "tomatoes", "peaches", "melons", "watermelons"]
favoritefruits = [fruits[0], fruits[2], fruits[3], fruits[7], fruits[8], fruits[13]]

To iterate you do not need to use i.
Instead, just use:

for fruit in fruits:
    if fruit in favoritefruits:
        print("I'm gonna buy some " + fruit + " because they are one of my favorite fruits.")
    else:
        print("I'm not going to buy " + fruit + ", I don't like them.")

Output:

I'm gonna buy some strawberries because they are one of my favorite fruits.
I'm not going to buy apples, I don't like them.
I'm gonna buy some bananas because they are one of my favorite fruits.
I'm gonna buy some pomegranates because they are one of my favorite fruits.
I'm not going to buy blueberries, I don't like them.
I'm not going to buy dragon fruits, I don't like them.
I'm not going to buy papayas, I don't like them.
I'm gonna buy some pears because they are one of my favorite fruits.
I'm gonna buy some oranges because they are one of my favorite fruits.
I'm not going to buy mango, I don't like them.
I'm not going to buy tomatoes, I don't like them.
I'm not going to buy peaches, I don't like them.
I'm not going to buy melons, I don't like them.
I'm gonna buy some watermelons because they are one of my favorite fruits.
Answered By: Andre Nevares

for i in fruits will return the fruits themselves and not the index and so when you do fruits[i] python expects an int but you gave it a string. You can do for i in range(len(fruits)) so that fruits[i] returns the fruit but in your code you only use the index to get the fruit so a much cleaner solution would be to rewrite for i in fruits into for fruit in fruits and simply use fruit inside the loop.

Answered By: mar1332244
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.