How can I create an empty list?

Question

For this exercise, are there any other options for creating an empty list?

Answer

There are two ways to create an empty list in Python. The most direct way is to create a variable and assign it an empty list by using a set of square brackets ([]) containing no items. The second way to create an empty list is to use the list class to create an empty list. Both methods achieve the same result and are showing in the following example code.

# Method 1

emptylist1 = []

# Method 2

emtpylist2 = list()
16 Likes

Is there a particular reason to choose one method over the other?

Someone correct me if I’m wrong, but I believe it’s just programmer preference. There appears to be no difference in the lists created:

# Method 1

emptylist1 = []

# Method 2

emptylist2 = list()

print (emptylist1)
print (emptylist2)

print (type(emptylist1))
print (type(emptylist2))

Output:

[ ]
[ ]
<class ‘list’>
<class ‘list’>

3 Likes

There isn’t, only the way they are created is different.

[]        # implicit

list()    # explicit

The implicit form forced Python to invoke an instance of the list class, while the latter is explicitly invoking a new instance.

Python is pretty good at recognizing type literals, but it still has to go through the motions so it gets assigned to memory correctly.

>>> a = []
>>> b = list()
>>> id(a)
45194632L
>>> id(b)
45237640L
>>> 

We can see that lists are independent.

7 Likes

The creation of lists in Python works same that languages like Java?
I mean that if I use the 2° of this methods can use more pre-built functions to work with the list?

1 Like

In Python, [] is seen by the interpreter as a list object so permits it to inherit all the attributes of that class.

x = [] is the same as x = list()

It is a recognized instance, either way.

1 Like