A program needs to convert a range into a collection that can be edited.
What You Need to Understand
list(iterable) constructs a mutable list from an iterable, such as a tuple, range, string or generator. Calling list() with no argument creates an empty list.
When to Use It
A program needs to convert a range into a collection that can be edited.
Step-by-Step Python Example
numbers = list(range(3))
letters = list("cat")
print(numbers)
print(letters)
numbers.append(3)
print(numbers)
How the Example Works
The range produces [0, 1, 2], and each character of the string becomes a separate list element.
Example Output
[0, 1, 2]
['c', 'a', 't']
[0, 1, 2, 3]
[5, 6]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
coordinates = (3, 6)
editable = list(coordinates)
editable[0] = 5
print(editable)
Important Behavior and Edge Cases
Calling list() on a huge or infinite iterable can exhaust memory or never finish. A list is not a deep copy of nested objects.
Try It Yourself
Convert a three-element tuple to a list and change its first item.
Common Beginner Mistakes
- Calling
list()on a huge or infinite iterable can exhaust memory or never finish. A list is not a deep copy of nested objects. - Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
list(iterable)constructs a mutable list from an iterable, such as a tuple, range, string or generator.- The range produces
[0, 1, 2], and each character of the string becomes a separate list element. - Calling
list()on a huge or infinite iterable can exhaust memory or never finish.