Python list() Function

Spread the love

The list() function is a built-in Python function that creates a list from an iterable object. An iterable can be anything that you can loop over, such as strings, tuples, dictionaries, or file objects. When list() is called with an iterable, it reads through the iterable one element at a time and adds each element to a new list.

Syntax:

The syntax of list() is straightforward:

list([iterable])

Parameters:

The list() function takes a single argument:

iterable (optional) – an object that could be a sequence like string, tuple or collection like set, dictionary or any iterator object.

Return Value:

The list() function returns a list.

  • If no parameters are passed, it returns an empty list
  • If iterable is passed as a parameter, it creates a list consisting of iterable’s items.

Creating Lists with list( )

Create a List From Strings

When list() is called with a string, it creates a list of individual characters:

string = "hello"
list_from_string = list(string)
print(list_from_string)  # Output: ['h', 'e', 'l', 'l', 'o']

Create a List From Tuples

Tuples can be converted to lists. This is useful for when you need a mutable version of a tuple.

tuple = (1, 2, 3)
list_from_tuple = list(tuple)
print(list_from_tuple)  # Output: [1, 2, 3]

Create a List From Dictionaries

When used on a dictionary, list() returns the keys of the dictionary.

dict = {'a': 1, 'b': 2, 'c': 3}
list_from_dict = list(dict)
print(list_from_dict)  # Output: ['a', 'b', 'c']

Create a List From Sets

Sets are unordered collections of unique elements. list() can be used to convert a set to a list.

set = {1, 2, 3, 4, 5}
list_from_set = list(set)
print(list_from_set)  # Output may vary in order, e.g., [1, 2, 3, 4, 5]

Create a List From a Range Object

list() can be used to materialize the numbers produced by range() into a list:

range_list = list(range(5))
print(range_list)  # Output: [0, 1, 2, 3, 4]

Creating an Empty List

Calling list() with no arguments gives you an empty list:

empty_list = list()
print(empty_list)  # Output: []

Create a List From an iterator object

Creating a list from an iterator object in Python is a common and straightforward operation. An iterator in Python is an object that adheres to the iterator protocol, which consists of the methods __iter__() and __next__(). The __iter__() method, which is called by the iter() function, returns the iterator object itself. The __next__() method is used to fetch the next item from a sequence, and it should raise a StopIteration exception when there are no more items to retrieve.

When you pass an iterator to the list() function, it calls the __next__() method repeatedly until the StopIteration exception is encountered. It collects all the items returned by __next__() into a new list object and returns this list.

You can create a custom objects that are iterable by defining the __iter__() and __next__() methods.

class CountDown:
    def __init__(self, start):
        self.start = start
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        self.start -= 1
        return self.start + 1

# Create an instance
countdown = CountDown(3)

# Create a list from the countdown iterator
countdown_list = list(countdown)
print(countdown_list)  # Output: [3, 2, 1]

In the CountDown class, the __iter__() method returns the object itself, making it an iterator. The __next__() method returns the next number in the countdown sequence each time it’s called. When it reaches zero, it raises StopIteration, which signals to the list() function that the iteration is complete.

Infinite Iterators

You should be careful with iterators that can potentially yield an infinite sequence. If you pass such an iterator to list(), it will attempt to consume it indefinitely and can cause your program to run out of memory and crash.

# An infinite iterator
def infinite_sequence():
    num = 0
    while True:
        yield num
        num += 1

# The following line is dangerous, as it will try to create an infinite list
# infinite_list = list(infinite_sequence())

# Instead, use islice from itertools to create a list from a slice of the iterator
from itertools import islice

finite_list = list(islice(infinite_sequence(), 10))  # Only take the first 10 elements
print(finite_list)  # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Conclusion

The list() function in Python is a testament to the language’s design philosophy of emphasizing code readability and simplicity. Whether you’re transforming a string into a list of characters, type casting objects, or creating an empty list as a starting point for data accumulation, list() is the go-to function. Its performance and flexibility make it an essential tool for data manipulation in Python.

Leave a Reply