0

I can't see the answer for this anywhere but I know it's a stupid question so sorry in advance!!

I have a list like this:

fullList = [("a","/a/"),("b","/b/"),("c","/c/"),("d","/d/"),("e","/e/")]

If I have the value, lets say c then how do I get it's index for the array?

If I use the index method it's doesn't work:

listIndex = fullList.index('c')

Any ideas?

Cheers and sorry if a really stupid question...

2
  • If I don't know what the second part is, /c/ ? Commented Oct 30, 2014 at 19:00
  • mcquaim, see my edit to my answer. It builds a list of the first parts of the tuples and matches on that. Commented Oct 30, 2014 at 19:08

3 Answers 3

3

you just need a list comprehension and use in operation :

>>> [fullList.index(i) for i in fullList if 'c' in i]
[2]

If you just want to check for first index you can use this:

>>> [fullList.index(i) for i in fullList if i[0]=='c']
[2]

Also note that you can use enumerate function in your list comprehension that have more performance here , (the order of index() is O(n)) you can refuse from an extra searching !

>>> [i for i,j in enumerate(fullList) if j[0]=='c']
[2]

>>> [i for i,j in enumerate(fullList) if 'c' in j]
[2]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for all the help everyone, sorted now!
1

A list's index() looks for equality on the elements of the list, so you want to provide the item that equals what you're looking for. Specifically, in this case, it would be:

listIndex = fullList.index(('c', '/c/'))

If you really need to search by the first element of the tuple, you can grab just the first one of each item and do .index on that:

listIndex = [ e[0] for e in fullList ].index('c')

Comments

0

Do you need the index or the full value ? In the second case:

>>> found = dict(fullList).get('c')
>>> print found
("c", "/c/")

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.