2

I have the following lists:

a = ["a", "b", "c", "d", "e", "f"]
b = [a[5], a[4], a[3]]

If I use b.index("f") I get 0. What I want it to output, however, is 5. How can I get the index of "f" in list a through the list b?

1
  • 1
    [a.index(e) for e in b] Commented Aug 25, 2018 at 15:57

3 Answers 3

4

You can't, because the elements in a are strings which don't "know" where they are in the list. Hence when you index them out of the list (e.g. a[5]), the strings can't tell you where they came from in the list.


I'm not sure what your aim is through creating this new list, but you could just store the indexes of the elements rather than the elements themselves in b.

e.g.

b = [5, 4, 3]

which would allow you to then create a function which would "get the index of [an element] in list a through list b:

def get_ind_in_a_thru_b(e):
    i = a.index(e)
    if i in b: return i
    else: raise ValueError

which works as if there were some magical method to get the index of elements in b as if they were in a:

>>> get_ind_in_a_thru_b('f')
5
>>> get_ind_in_a_thru_b('g')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in get_ind_in_a_thru_b
ValueError: 'g' is not in list
>>> get_ind_in_a_thru_b('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in get_ind_in_a_thru_b
ValueError

note how even though 'a' is in the list a, since it is not in the list b, it is not returned

Sign up to request clarification or add additional context in comments.

Comments

2

This isn't possible. Elements of b are resolved to strings and lose all knowledge of their indices in a. You can write a small class to store the value and index:

from operator import attrgetter

a = ["a", "b", "c", "d", "e", "f"]

class GetItemPos():
    def __init__(self, L, idx):
        self.idx = idx
        self.var = L[idx]

b = [GetItemPos(a, 5), GetItemPos(a, 4), GetItemPos(a, 3)]

indices = list(map(attrgetter('idx'), b))  # [5, 4, 3]
values = list(map(attrgetter('var'), b))   # ['f', 'e', 'd']

Comments

0

In this way, b would be ["f", "e", "d"] and the indexes of that elements are 0,1,2. You can create b in this way, though:

b = [a.index(a[5]), a.index(a[4]), a.index(a[3])]

Otherwise, if you want indexes and values you can use a dictionary:

b = {a[3]: a.index(a[3]), a[4]: a.index(a[4]),a[3]: a.index(a[3])}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.