fabiankuenzer
fabiankuenzer

Reputation: 148

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?

Upvotes: 2

Views: 50

Answers (2)

Andreas
Andreas

Reputation: 9207

You can zip the lists:

longest_streak_ids = [i for i, x in zip(id_list, streak_length_list) if x == longest_streak]

Out[15]: [3, 4, 5]

Upvotes: 1

Guy
Guy

Reputation: 50899

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]

Upvotes: 2

Related Questions