How to Create an Empty List in Python



Python


In this article, we show how to create an empty list in Python.

So lists are an very important data type in programming.

Lists can be used for all types of reasons.

Lists are especially important when you have more than one piece of data that are related in some form. For example, you may have a list of numbers. You may have a list of places to travel to. Lists in Python don't have to be the same data type, but usually for all practical purposes are.

When writing a program, you may need to start off as an empty list.

This is usually the case when you are accepting input from ma user. You want the list to blank at first. Then the user gives input (more than one piece of data). We can then store this data in a list.

To keep this simple, let's create an empty list.

How to Create an Empty List

There are 2 ways to create an empty list in Python.

One of the ways is shown below.



The other way to create an empty list is shown below.



So, both of these methods produce the same result. They create an empty list.

Just so that you can see why an empty list would be used, let's examine the program below.

Below is a program that calculates the sum of numbers that a user enters.

In this program, we create an empty list.

We then accept input from the user, asking the user to enter in numbers separated by a comma.

We store these numbers in the empty list.

We then have to split the numbers, so we do this through the split() function, specifying a ',' as the delimiter.

We create a new list with the numbers now split.

We then can use a for loop to add up all the numbers giving the sum.

We'll go over this again.

This is the code shown below.



So, we'll go through the code one more time.

This is a program that finds the sum of numbers that a user enters.

We first create an empty list, named numbers. We do this through the line, numbers=[]

We then create a variable called total. We set it equal to 0 initially. This variable will hold the total sum of the numbers.

We set the numbers variable equal to input(). This is so that we can get the numbers that the user enters. These numbers are separated by a comma.

We then split the numbers entered by the delimiter, ",". This is because we ask the user to enter in the numbers separated by a comma.

We store this split string into the splitnumbers list.

Once this is all done, we use a for loop to go through each of the numbers. With each number, we add the number to total. In this way, in the end, total contains the complete sum of the list.

We then print out this sum.

So, you can see how important empty strings can be in Python and why we would use them.


Related Resources

How to Show All Tables of a MySQL Database in Python

How to Count the Number of Rows in a MySQL Table in Python



HTML Comment Box is loading comments...