89DEVs

Python: How to create an empty list?

How to create an empty list in Python?

To create an empty list in Python, use square brackets or the list() function. Using square brackets is faster and more efficient than using the list() function and is therefore the recommend way of creating an empty list. It is also more concise and therefore a more pythonic way of creating lists.

create an empty list using square brackets

To create an empty list use square brackets as shown below. # create empty list using square bracket myList = [] print(myList) The empty list is created and printed. [] To check if the created object is a list, use the type() function: myList = [] print(type(myList)) The Python interpreter confirms that a list was created.

create an empty list using list() function

To create an empty list in Python, use the list() function as shown below. If the list function is called without any argument, an empty list is created. It is also possible to create an non-empty list by passing values to the list() function. # create empty list using list() function myEmptyList = list() myNonEmptyList = list([1, 2, 3]) print(myEmptyList) print(myNonEmptyList) In this example two lists are created. One empty list by passing no values to the list() function and one list filled with the values we passed. [] [1, 2, 3]

Add elements to an empty list

After the list is created, we can add elements to it. Lists offer two methods for adding elements: The append() method adds the element to the end of the list The insert() method adds the element at the specified index. If index is set to 0, the element is added at the start of the list. # add element to an empty list # create empty list myList = [] # append at the end of list myList.append(2) # insert at the start of list (index = 0) myList.insert(0, 1) # print the list print(myList) In this example we add elements using the append() method and the insert() method. First the integer 2 is added to the end of the list. Then the integer 1 is added at index 0, which is the start of the list. Finally the list is printed and contains both integers. [1, 2]

check if list is empty

To check if the created list is empty use the not in operator. # check if list is empty myList = [] if not myList: True In this code the list myList is empty and therefore considered False in Python. True is returned because the list is not True. True Other ways of checking if a list is empty are using the len() function to determining the length of the list or comparing the list to an empty list. However the recommended way of checking for an empty list is the if not operator, because it is fast and a very pythonic way of doing the operations.

                
        

Summary


Click to jump to section