banner



Initializing A List In Python

Python Empty List Tutorial – How to Create an Empty List in Python

If you want to learn how to create an empty list in Python efficiently, then this article is for you.

You will learn:

  • How to create an empty list using square brackets [].
  • How to create an empty list using list().
  • Their use cases.
  • How efficient they are (ane is faster than the other!). We will use the timeit module to compare them.

Allow'south brainstorm! ✨

๐Ÿ”น Using Foursquare Brackets

You can create an empty list with an empty pair of square brackets, like this:

image-131

๐Ÿ’ก Tip: We assign the empty list to a variable to use it later in our program.

For example:

                num = []              

The empty list will have length 0, as you tin can meet correct here:

                >>> num = [] >>> len(num) 0              

Empty lists are falsy values, which ways that they evaluate to False in a boolean context:

                >>> num = [] >>> bool(num) False              

Add Elements to an Empty List

Yous can add elements to an empty list using the methods append() and insert():

  • append() adds the element to the finish of the list.
  • insert() adds the chemical element at the particular index of the list that you cull.

Since lists can be either truthy or falsy values depending on whether they are empty or non when they are evaluated, y'all tin can use them in conditionals like this:

                if num: 	print("This list is not empty") else: 	print("This list is empty")              

The output of this code is:

                This list is empty              

Considering the list was empty, so information technology evaluates to False.

In general:

  • If the list is not empty, it evaluates to True, and so the if clause is executed.
  • If the list is empty, information technology evaluates to False, then the else clause is executed.

Example:

In the example below, we create an empty list and assign it to the variable num. Then, using a for loop, nosotros add a sequence of elements (integers) to the list that was initially empty:

                >>> num = [] >>> for i in range(3, 15, two): 	num.append(i)              

We check the value of the variable to meet if the items were appended successfully and confirm that the listing is not empty anymore:

                >>> num [three, 5, 7, 9, eleven, 13]              

๐Ÿ’ก Tip: Nosotros commonly utilize append() to add the first element to an empty list, merely y'all can besides add this element calling the insert() method with index 0:

                >>> num = [] >>> num.insert(0, i.five) # add the float 1.5 at alphabetize 0 >>> num [1.5]              

๐Ÿ”ธ Using the list() Constructor

Alternatively, you lot can create an empty listing with the type constructor list(), which creates a new list object.

According to the Python Documentation:

If no argument is given, the constructor creates a new empty list, [].
image-132

๐Ÿ’ก Tip: This creates a new list object in retention and since nosotros didn't pass whatsoever arguments to list(), an empty list will be created.

For example:

                num = listing()              

This empty list will have length 0, as yous tin see right here:

                >>> num = list() >>> len(num) 0              

And it is a falsy value when it is empty (it evaluates to False in a boolean context):

                >>> num = list() >>> bool(num) False              

Instance:

This is a fully functional list, so we can add elements to information technology:

                >>> num = list() >>> for i in range(3, 15, 2): 	num.suspend(i)              

And the result will be a non-empty list, as you can run into correct here:

                >>> num [iii, five, 7, 9, 11, 13]              

๐Ÿ”น Use Cases

  • We typically use listing() to create lists from existing iterables such equally strings, dictionaries, or tuples.
  • You will ordinarily see square brackets [] being used to create empty lists in Python because this syntax is more concise and faster.

๐Ÿ”ธ Efficiency

Wait! I merely told you lot that [] is faster than list()...

Just how much faster?

Let'southward cheque their time efficiencies using the timeit module.

To use this module in your Python program, you lot demand to import it:

                >>> import timeit              

Specifically, we will use the timeit part from this module, which you can call with this syntax:

image-129

๐Ÿ’ก Tip: The code is repeated several times to reduce time differences that may arise from external factors such as other processes that might exist running at that particular moment. This makes the results more reliable for comparison purposes.

๐Ÿšฆ On your marks... become prepare... ready! Here is the code and output:

Commencement, we import the module.

                >>> import timeit              

Then, we start testing each syntax.

Testing []:

                >>> timeit.timeit('[]', number=10**4) 0.0008467000000109692              

Testing list():

                >>> timeit.timeit('listing()', number=10**iv) 0.002867799999989984              

๐Ÿ’ก Tip: Find that the code that you want to time has to be surrounded by single quotes '' or double quotes "". The fourth dimension returned by the timeit function is expressed in seconds.

Compare these results:

  • []: 0.0008467000000109692
  • list(): 0.002867799999989984

You can run into that [] is much faster than list(). There was a difference of approximately 0.002 seconds in this exam:

                >>> 0.002867799999989984 - 0.0008467000000109692 0.0020210999999790147              

I'm certain that you lot must be asking this correct now: Why is list() less efficient than [] if they do exactly the same thing?

Well... list() is slower considering it requires looking up the name of the function, calling it, and then creating the listing object in retentiveness. In contrast, [] is like a "shortcut" that doesn't require and then many intermediate steps to create the list in retention.

This time difference will not impact the performance of your plan very much but information technology's nice to know which one is more efficient and how they work backside the scenes.

๐Ÿ”น In Summary

You can create an empty list using an empty pair of foursquare brackets [] or the blazon constructor listing(), a born function that creates an empty list when no arguments are passed.

Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

I really hope that you liked my commodity and found it helpful. At present you can create empty lists in your Python projects. Bank check out my online courses. Follow me on Twitter. ⭐️

If you want to swoop deeper into lists, you may like to read:

  • Python Listing Append – How to Add an Element to an Assortment, Explained with Examples
  • The Python Sort List Array Method – Ascending and Descending Explained with Examples
  • Python Listing Suspend VS Python List Extend – The Difference Explained with Array Method Examples


Learn to code for free. freeCodeCamp's open source curriculum has helped more than than 40,000 people go jobs as developers. Get started

Initializing A List In Python,

Source: https://www.freecodecamp.org/news/python-empty-list-tutorial-how-to-create-an-empty-list-in-python/

Posted by: samonsatrom1955.blogspot.com

0 Response to "Initializing A List In Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel