Intrepidity
Intrepidity

Reputation: 103

How to find the index of a missing element?

Let's say you have the following lists:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

How would I write a loop that identifies that the "pear" element is missing in the "fruits" list's 2nd index?

I do know the first step begins with:

for element in fruit_types:
    if element not in fruits:

But I am completely lost where else to go from here.

Upvotes: 0

Views: 991

Answers (4)

hypercube
hypercube

Reputation: 1

You could do:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missing_elements = []
for element in fruit_types:
    if(element not in fruits):
        missing_elements.append(element)
print(missing_elements)
>>> ["pear"]

Create an empty list, then add to that list if the element is not in fruits.

Upvotes: 0

Snuffles
Snuffles

Reputation: 507

The above set differences work. But in case you wanted code that only checks if one of the two lists has missing elements (In your style). You could use the enumerate function.

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

def find_missing_index():
    for index, element in enumerate(fruit_types):
        if element not in fruits:
            print(fruit_types[index], index)

def main():
    find_missing_index()

if __name__ == '__main__':
    main()

No doubt you wanted the set difference code however which there are plenty of examples from others.


For added performance, it would be wise to convert fruits to a set in advance.

fset = set(fruits)
for index, element in enumerate(fruit_types):
    if element not in fset:
        print(fruit_types[index], index)

This reduces the membership test to constant, O(1) lookup.

Upvotes: 3

Nabin
Nabin

Reputation: 11776

You can use difference operation on set to find this.

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = list(set(fruits_types) - set(fruit))
print missings

If this is cool, then why use loops?

Then to get index of the missing item:

for missing in missings:
    print fruit_types.index(missing)

Upvotes: 1

Reblochon Masque
Reblochon Masque

Reputation: 36682

Using sets difference, and finding the index:

fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]

missings = set(fruit_types) - set(fruits)
for missing in missings:
    print(fruit_types.index(missing))

output:

1  # which is the index of the missing element in fruit_types

Upvotes: 0

Related Questions