Get startedGet started for free

Holistic conversion loop

A list of all possible Pokémon types has been loaded into your session as pokemon_types. It's been printed in the console for convenience.

You'd like to gather all the possible pairs of Pokémon types. You want to store each of these pairs in an individual list with an enumerated index as the first element of each list. This allows you to see the total number of possible pairs and provides an indexed label for each pair.

The below loop was written to accomplish this task:

enumerated_pairs = []

for i,pair in enumerate(possible_pairs, 1):
    enumerated_pair_tuple = (i,) + pair
    enumerated_pair_list = list(enumerated_pair_tuple)
    enumerated_pairs.append(enumerated_pair_list)

Let's make this loop more efficient using a holistic conversion.

This exercise is part of the course

Writing Efficient Python Code

View Course

Exercise instructions

  • combinations from the itertools module has been loaded into your session. Use it to create a list called possible_pairs that contains all possible pairs of Pokémon types (each pair has 2 Pokémon types).
  • Create an empty list called enumerated_tuples above the for loop.
  • Use a built-in function to convert each tuple in enumerated_tuples to a list.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Collect all possible pairs using combinations()
possible_pairs = [*____(pokemon_types, ____)]

# Create an empty list called enumerated_tuples
____ = ____

for i,pair in enumerate(possible_pairs, 1):
    enumerated_pair_tuple = (i,) + pair
    enumerated_tuples.append(enumerated_pair_tuple)

# Convert all tuples in enumerated_tuples to a list
enumerated_pairs = [*____(____, enumerated_tuples)]
print(enumerated_pairs)
Edit and Run Code