Skip to content
Advertisement

Iterating through two lists and return indices

I created a habit tracker app and one of the functions is to return the longest uninterrupted streak of done habits. If there are two or more habits with the same streak length, I want to return all of them. Therefore I saved the habit IDs in an id_list and the respective streak lengths in the streak_length_list.

Let me give you an example:

id_list = [1, 2, 3, 4, 5, 6]
streak_length_list = [2, 5, 6, 6, 6, 1]
longest_streak = max(streak_length_list)
longest_streak_ids = []

How can I iterate through the id_list and the streak_length_list simultaneously and append the respective ID to the longest_streak_id list if its length equals the longest_streak value?

Advertisement

Answer

You don’t need to iterate over both lists, only over streak_length_list and use enumerate to get the value and index of all items. If the value equals to longest_streak use the index to get the id from id_list

longest_streak_ids = [id_list[i] for i, x in enumerate(streak_length_list) if x == longest_streak]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement