Make a List Empty Again Python

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

If yous desire to acquire how to create an empty list in Python efficiently, then this article is for you lot.

You will learn:

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

Let's begin! ✨

🔹 Using Foursquare Brackets

Y'all tin create an empty list with an empty pair of foursquare brackets, like this:

image-131

💡 Tip: We assign the empty list to a variable to utilise it subsequently in our plan.

For example:

                num = []              

The empty list will have length 0, as you can see right hither:

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

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

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

Add together Elements to an Empty List

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

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

Since lists can be either truthy or falsy values depending on whether they are empty or not when they are evaluated, you 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              

Because the list was empty, so information technology evaluates to Simulated.

In full general:

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

Example:

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

                >>> num = [] >>> for i in range(iii, fifteen, two): 	num.suspend(i)              

We check the value of the variable to see if the items were appended successfully and confirm that the list is non empty anymore:

                >>> num [3, 5, 7, ix, 11, 13]              

💡 Tip: We unremarkably utilize append() to add the outset element to an empty list, simply you tin also add this element calling the insert() method with index 0:

                >>> num = [] >>> num.insert(0, i.5) # add the float ane.5 at index 0 >>> num [1.5]              

🔸 Using the list() Constructor

Alternatively, you tin 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 memory and since we didn't pass any arguments to listing(), an empty list volition exist created.

For example:

                num = list()              

This empty list will have length 0, as you can see correct here:

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

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

                >>> num = listing() >>> bool(num) Fake              

Example:

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

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

And the result will be a not-empty list, as yous tin can see right here:

                >>> num [3, 5, 7, 9, 11, thirteen]              

🔹 Utilize Cases

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

🔸 Efficiency

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

Just how much faster?

Let's check their fourth dimension efficiencies using the timeit module.

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

                >>> import timeit              

Specifically, we will use the timeit part from this module, which y'all can phone call with this syntax:

image-129

💡 Tip: The code is repeated several times to reduce fourth dimension differences that may arise from external factors such every bit other processes that might be running at that detail moment. This makes the results more reliable for comparing purposes.

🚦 On your marks... get set... ready! Here is the code and output:

First, we import the module.

                >>> import timeit              

Then, we outset testing each syntax.

Testing []:

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

Testing list():

                >>> timeit.timeit('list()', number=10**4) 0.002867799999989984              

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

Compare these results:

  • []: 0.0008467000000109692
  • list(): 0.002867799999989984

Y'all can run across that [] is much faster than list(). There was a difference of approximately 0.002 seconds in this examination:

                >>> 0.002867799999989984 - 0.0008467000000109692 0.0020210999999790147              

I'm certain that y'all must be request this right now: Why is list() less efficient than [] if they practice exactly the aforementioned affair?

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

This time divergence will not affect the functioning of your plan very much but it'south nice to know which one is more than efficient and how they work behind the scenes.

🔹 In Summary

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

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

I really hope that you liked my article and found it helpful. Now you lot can create empty lists in your Python projects. Cheque out my online courses. Follow me on Twitter. ⭐️

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

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


Acquire to code for gratuitous. freeCodeCamp'southward open source curriculum has helped more than than 40,000 people get jobs as developers. Get started

stevenswaystal84.blogspot.com

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

0 Response to "Make a List Empty Again Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel