Empty Lists

Empty lists

We often create empty lists with the intent of filling in the values at a later time.


The [ ] operator

The [ ] operator is the easiest way to create an empty list.

x = [ ]

This creates an empty list and assigns it to the variable "x".

The list() function

Another way to create an empty list is by calling the list() function with no parameters. The function will return an empty list


x = list()

Creating a literal list of empty lists

Now we discuss creating a list of empty lists (empty sub-lists). If the number of sub-list is small, we can specify them literally.

x = [
    [],
    [],
    [],
]




Creating a list of empty lists with a list comprehension

If the number of sub-lists is large, we can use a list comprehension to generate the list. This reduces the amount of typing we need to do.


x = [ [] for i in range(10) ]


Avoid using the repeat operator

Lists, like other sequence types, support the repeat operator (*). It may be tempting to use the repeat operator to generate a list of empty lists.


This will NOT create multiple lists. Instead, it will create ONE list and fill the main list with multiple references to that ONE list.



x = [ [] ] * 10  # don't do this!


Stop and compare this diagram to the previous one.




No comments:

Post a Comment