finding an element from one list in another list in python

10,346

Solution 1

Looking up the position of an item in a list is not a very efficient operation. A dict is a better data structure for this kind of task.

>>> d = {k:v for v,k in enumerate(list_one)}
>>> print(*(d[k] for k in list_two))
8 5 12 12 15

If your list_one is always just the alphabet, in alphabetical order, it's probably better and simpler to get something working by using the builtin function ord.

Solution 2

Adding to @wim's answer, could be done with a simple comprehension.

>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]

Solution 3

you can iterate thought the list :

>>> for i in range(len(list_two)):
...     for j in range(len(list_one)):
...             if list_two[i]==list_one[j]:
...                     list_3.append(j)
>>> list_3
[8, 5, 12, 12, 15]

but wim's answer is more elegant !

Share:
10,346
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

    list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    
    list_two = ["h","e","l","l","o"]
    

    my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

    so if the user did input hello the computer would return 85121215 (being the position of the entries)

    is there a possible way to do this

  • Admin
    Admin about 7 years
    thanks! this also helps me. I was looking for a way to store the output as a variable and yours does that. thanks!
  • Astrid
    Astrid over 5 years
    This is much cleaner.