Skip to content
Advertisement

How to find specific item/s in list/s in Python

I am new to this and I would to find specifc index of item from lists in list in Python. It only work with multiple lists in one list, and I would to know if you know much simple way to search trought all existing and new added list to find specific index of an item and more than in two lists. I would be greatful for help.

main_list = [[0, 1, 1, 3], [1, 'b', 'c', 'd'], [0, 'b', 1, 'd']]

print(f'MAIN LIST: {main_list}')

find_in_list = False # put number of list if specific search is needed ### find_in_list = 1
find_item = 'b' # item that you want to find in one or multiple lists

count_number_of_lists = -1

add_item_index = []
store_items_index = []
item_index_of_store_items_index = 0
list_index_and_item_index = []

for sub_list_index, sub_list_others in enumerate(main_list):

    count_number_of_lists += 1

    if find_in_list == False:
        sub_list = main_list[sub_list_index] # no specific list

        for sub_list_index_2, sub_list_others_2 in enumerate(sub_list):
            if sub_list_others_2 == find_item:  # find exactly same item as needed to be found
                add_item_index.append(sub_list_index_2)
                print(add_item_index)

    else:
        sub_list = main_list[find_in_list] # specific list

        for sub_list_index_2, sub_list_others_2 in enumerate(sub_list):
            if sub_list_others_2 == find_item: # find exactly same item as needed to be found
                add_item_index.append(sub_list_index_2)

    store_items_index.append(add_item_index)
    add_item_index = []
    for sub_index, sub_other in enumerate(store_items_index):
        item_index_of_store_items_index = store_items_index[sub_index]

    list_index_and_item_index.append([count_number_of_lists, item_index_of_store_items_index])
    if find_in_list == False:
        print(f'LIST INDEX: {count_number_of_lists}, ITEM INDEX: {item_index_of_store_items_index}')

if find_in_list == False:
    print(f'List of [LIST INDEX and, [ITEM INDEX]]: {list_index_and_item_index}') # all LIST INDEX and ITEM INDEX in one list
    print(f'ALL ITEMS INDEX: {store_items_index}') # all index of items in one list

else:
    print(f'LIST INDEX: {count_number_of_lists}, ITEM INDEX: {item_index_of_store_items_index}')

Advertisement

Answer

main_list = [[0, 1, 1, 3], [1, 'b', 'c', 'd'], [0, 'b', 1, 'd']]

find_in_list = False
find_item = 'b'

if not find_in_list:
    list_indices = list(range(len(main_list)))
else:
    list_indices = [find_in_list]

res = []
for i in list_indices:
    occurrences = []
    for j, e in enumerate(main_list[i]):
        if e == find_item:
            occurrences.append(j)
    res.append([i, occurrences])
print(res)

prints

[[0, []], [1, [1]], [2, [1]]]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement