Trent Roberts Trent Roberts - 6 months ago 16
Python Question

Cross Referencing Lists in Python

I am trying to make a function that takes an input, compares that input to a list of lists and returns an item from another list with the same number of objects.

Example:

list_1=[[1,2,3],[4,5],[6,7,8]]

list_2=['a','b','c']



  • If
    input
    is 1, 2 or 3 function returns
    'a'

  • If
    input
    is 4 or 5 function returns
    'b'

  • If
    input
    is 6, 7 or 8 function returns
    'c'



I'm new to python and have been thinking about the problem for a while and looking around for clues with no results. Any tips/clues that might help me figure this out would be appreciated! Thanks!

FTA FTA
Answer

You can loop through each list in list_1 and check if the input is in one. If it is, you can print the corresponding index of list_2 (assuming it is composed only of single values), which you obtain by using enumerate in the loop.

input = 1
for idx,i in enumerate(list_1):
    if input in i:
        return list_2[idx]

In this case, I returned 'a'.

Comments