5 Best Ways to Convert a Python Iterable to a Sequence

πŸ’‘ Problem Formulation: In Python, converting iterables to sequences is a common task, typically when one needs to store the results of iterable objects such as generators, sets, or dict keys/values. For instance, converting a generator that yields prime numbers into a list or tuple for indexed access or to perform other list-specific operations.

Method 1: Using the list() Constructor

Converting an iterable to a list is straightforward using Python’s built-in list() constructor. This approach provides a simple and direct way to turn any iterable into a list, which is a mutable sequence type, allowing for subsequent element modification.

Here’s an example:

primes = (x for x in range(2, 10) if all(x % i != 0 for i in range(2, x)))
primes_list = list(primes)

Output:

[2, 3, 5, 7]

This example demonstrates the conversion of a generator expression that generates prime numbers into a list. The list() constructor iterates over the generator and stores each yielded value, creating a list of prime numbers.

Method 2: Using the tuple() Constructor

Similarly to lists, the tuple() constructor can be used to convert an iterable to an immutable sequence type known as a tuple. This method is best when the sequence does not need to change after creation.

Here’s an example:

fibonacci = (0, 1, 1, 2, 3, 5, 8)
fibonacci_tuple = tuple(fibonacci)

Output:

(0, 1, 1, 2, 3, 5, 8)

Here, a Fibonacci series represented as a tuple is passed to the tuple() constructor, which creates an identical tuple. Since tuples are immutable, this series cannot be changed after conversion.

Method 3: Using a Sequence Comprehension

Using comprehension is a concise way to build a list or tuple by iterating over an iterable. List comprehensions are enclosed in square brackets, while tuple comprehensions are generated with rounded parentheses.

Here’s an example:

characters = 'abcde'
char_list = [char for char in characters]

Output:

['a', 'b', 'c', 'd', 'e']

The example shows a list comprehension that iterates over a string iterable. Each character is added to a new list, creating a list of individual characters.

Method 4: Using the slice operator

The slice operator can convert an iterable to a sequence when combined with type conversion. This method is especially useful to create a slice of the iterable and simultaneously convert it into a list or tuple.

Here’s an example:

numbers = range(10)
sliced_list = list(numbers[:5])

Output:

[0, 1, 2, 3, 4]

This snippet first creates a range object, which is an iterable that produces numbers from 0 up to (but not including) 10. The slice operator is used to get the first five elements, and the list() constructor converts this slice into a list.

Bonus One-Liner Method 5: Using unpacking with list/tuple constructors

Python supports using the asterisk (*) to unpack an iterable directly within the list or tuple constructor, which can be a more idiomatic and shorter way of converting an iterable.

Here’s an example:

odd_numbers = {1, 3, 5, 7, 9}
unpacked_list = [*odd_numbers]

Output:

[1, 3, 5, 7, 9]

The unpacking operator (*) is used within the list brackets to convert the set of odd numbers into a list. Note that the order is not guaranteed when unpacking from a set.

Summary/Discussion

  • Method 1: list() Constructor. Universal method, mutable result. May not be efficient for large iterables.
  • Method 2: tuple() Constructor. Creates immutable sequences, which is an advantage for fixed data. Less flexible than lists due to immutability.
  • Method 3: Sequence Comprehension. Offers fine-grained control, can include conditional logic. May be less readable for complex transformations.
  • Method 4: Slice Operator. Ideal for converting and slicing in one step. Requires an extra step (type conversion) for types other than lists.
  • Method 5: Unpacking. Syntactically concise. Destroys the original order for unordered iterables like sets.