LokiH LokiH - 5 months ago 25
Python Question

finding variable in list

I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,

list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]

With these lists, if the user inputs "a" then the computer works out that it is the first string in the list and picks out "1" from list2, or if they inputted "c", then it finds "3". However, due to the lists expanding and shrinking regularly, I can't use:

if input == list[0]:
variable = list2[0]

I tried doing:

y = 0
x = 1
while x == 1:
if input == list[y]:
variable = list2[y]
x = 2
y = y + 1

but that didn't work, so is there anyway that this can be done? or am I being a mong and missing the obvious...


Option 1

This is probably the simplest solution:

>>> list1 = ["a", "b", "c", "d"]
>>> list2 = [1, 2, 3, 4]
>>> mapping = dict(zip(list1, list2))
>>> mapping['b']

BTW, to understand what happened:

>>> zip(list1, list2)
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> dict(zip(list1, list2))
{'a': 1, 'c': 3, 'b': 2, 'd': 4}

Option 2

Anyway, you asked how to get the index in the list. Use index:

>>> list1.index('c')

And then:

>>> list2[list1.index('c')]

Also... don't name your lists list because that way you are "hiding" the builtin list.