1

As an example, right now I have a list of:

list = [[1276, 'c'], [910, 'b'], [819, 'o'], [759, 'z'], [699, 'l']]

and I would like to index this list for only a specific letter, for instance:

index = list.index('c')

As is, I realize that I'm going to get a ValueError, and I've learned that to make this work, I would need to index for the entire sublist.

index = list.index([1276,'c'])

Is there anyway I can work around having to index for the list as a whole, given that I don't currently know the integer value?

I hope this all makes sense, and if needed, I can certainly provide further clarification.

Thank you

1
  • 1
    You could iterate over the list of lists and build a dictionary of indices for each item then use the dictionary. enumerate() might be helpfull. Commented Mar 23, 2019 at 1:21

5 Answers 5

1

If you know that the inner lists will only have two values, you could create your own function to get the first item that matches with next() and enumerate():

def get_index(lst, item):
    return next((i for i, (_, x) in enumerate(lst) if x == item), None)

Which works like this:

print(get_index(lst, 'c')) # 0
print(get_index(lst, 'b')) # 1
print(get_index(lst, 'o')) # 2
print(get_index(lst, 'z')) # 3
print(get_index(lst, 'l')) # 4
print(get_index(lst, 'g')) # None

And returns None if an item was not found.

As suggested in the comments, a nicer solution would be to create a dictionary of index mappings:

def get_index(lst, item):
    indices = {x: i for i, (_, x) in enumerate(lst)}
    return indices.get(item)
Sign up to request clarification or add additional context in comments.

Comments

1

Declaring a class whose instances are "equal" to any value can help.

class Any:
    def __eq__(self, other):
        return True

list = [[1276, 'c'], [910, 'b'], [819, 'o'], [759, 'z'], [699, 'l']]
index = list.index([Any(), 'c'])
print(index)

Comments

1

You could do it with a list comprehension that only returns the letter part of the tuple. The index will be the same.

index = [c for _,c in list].index('c')

Comments

1

Instead of directly iterating over the items in a list AKA for i in list, you can iterate an integer value over the length of the list AKA for i in range(len(list)).

Here is an example of how to obtain the index of the correct sublist.

list = [[1276, 'c'], [910, 'b'], [819, 'o'], [759, 'z'], [699, 'l']]
for i in range(len(list)):
    if 'c' in list[i]:
        index = i
        break

3 Comments

Wouldn't you need two numbers to identify the location of an item in a list of lists?
My example only shows how to get the index of the correct sublist yeah. To get the correct index within the sublist, the solution is already provided in the question itself: index2 = list[i].index('c')
@wwii: The index of the character is always [-1] or [1] within the sublist. So here the main task is just to find the index of the sublist which contains the character always at position -1 or 1
0

Lookups using dictionaries are often faster, so you can build a dictionary, for example like this:

list_dct  = dict([ [y, [i,x,y]] for i, (x, y) in enumerate(mylist)])
#=> {'c': [0, 1276, 'c'], 'b': [1, 910, 'b'], 'o': [2, 819, 'o'], 'z': [3, 759, 'z'], 'l': [4, 699, 'l']}

In this way you can access the index as:

list_dct['o'][0] #=> 2


If you can get rid of the index you can simply convert your list to a dict, then access by the letter to get the integer:

list_dct = dict([ [y,x] for i, (x, y) in enumerate(mylist)])

list_dct #=> {'c': 1276, 'b': 910, 'o': 819, 'z': 759, 'l': 699}

list_dct['c'] #=> 1276


Remember that duplicated keys in dictionaries are not allowed.

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.