Home > Enterprise >  Which item in list - Python
Which item in list - Python

Time:10-18

I am making a console game using python and I am checking if an item is in a list using:

    if variable in list:

I want to check which variable in that list it was like list[0] for example. Any help would be appreciated :)

CodePudding user response:

Using a librairy you could use numpy's np.where(list == variable). In vanilla Python, I can think of something like:

idx = [idx for idx, item in enumerate(list) if item == variable][0]

But this solution is not fool proof, for instance, if theres no matching results, it will crash. You could complete this using an if right before:

if variable in list:
    idx = [idx for idx, item in enumerate(list) if item == variable][0]
else:
    idx = None

CodePudding user response:

I understand that you want to get a sublist containing only the elements of the original list that match a certain condition (in your example case, you want to extract all the elements that are equal to the first element of the list).

You can do that by using the built-in filter function which allows you to produce a new list containing only the elements that match a specific condition.

Here's an example:

a = [1,1,1,3,4]
variable = a[0]
b = list(filter(lambda x : x == variable, a)) # [1,1,1]

CodePudding user response:

This answer assumes that you only search for one (the first) matching element in the list.

Using the index method of a list should be the way to go. You just have to wrap it in a try-except statement. Here is an alternative version using next.

def get_index(data, search):
    return next((index for index, value in enumerate(data) if value == search), None)


my_list = list('ABCDEFGH')
print(get_index(my_list, 'C'))
print(get_index(my_list, 'X'))

The output is

2
None

CodePudding user response:

You can do it using the list class attribute index as following:

   list.index(variable)

Index gives you an integer that matches the location of the first appearance of the value you are looking for, and it will throw an error if the value is not found.

If you are already checking if the value is in the list, then within the if statement you can get the index by:

if variable in list:
    variable_at = list.index(variable)

Example:

foo = ['this','is','not','This','it','is','that','This']
if 'This' in foo:
    print(foo.index('This'))

Outputs:

3

Take a look at the answer below, which has more complete information.

Finding the index of an item in a list

CodePudding user response:

assuming that you want to check that it exists and get its index, the most efficient way is to use list.index , it returns the first item index found, otherwise it raises an error so it can be used as follows:

items = [1,2,3,4,5]
item_index = None
try:
    item_index = items.index(3)  # look for 3 in the list
except ValueError:
    # do item not found logic
    print("item not found")  # example
else:
    # do item found logic knowing item_index
    print(items[item_index])  # example, prints 3

also please avoid naming variables list as it overrides the built-in function list.

  • Related