Search code examples
pythonpython-itertools

itertools returning which list it found a match from


I'm new so bear with me.. I could create two separate for loops but I like this method since I'll probably iterate through multiple lists and this is less code. Is it possible in itertools? As I understand it, it creates one list out of the two so I might be out of luck.

import itertools

a = [0, 1, 2]
b = [3, 4, 5]


def finditem(n):
    for i in itertools.chain(a, b):
        if i == n:
            print(n)  #  here i want (n) and (a or b)


n = 3
finditem(n)

Solution

  • I think what you want is:

    • given a list of lists and an item to find if it exists in that list
    • tell me what list that item was found in.

    You should probably create a dictionary with your keys being what that list is called and the values for the things in that collection

    my_lists = {'a': [0, 1, 2], 'b': [3, 4, 5]}
    
    def find_item(my_lists, item_to_find):
        for key in my_lists:
            if item_to_find in my_lists[key]:
                print(key)
    n=3
    find_item(my_lists, n)