Ways to create a list of zeros in Python.
List are highly versatile and the process of creation of a list can be done in several ways, all of which will be thoroughly demonstrated in this tutorial.
Method 1:
- Create a list with one zero as its element.
- Repeat this list the required times using the
*
operator.
# Create a list of zeros in Python list_zero = [0] #List with element 0 # Use the * operator to repeat this list list_new = list_zero * 10 print(list_new) # Output [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In the above sample code, we use the *
operator to create a list of zeros in Python.
Alternatively, the itertools can also be utilized to create a list of zeros in Python.
The repeat function from this library can create an iterator by repeating a given object a specified number of times.
Method 2:
- Use the
repeat()
function to repeat the value. - Use the
list()
function to convert the resultant object to a list.
# Create a list of zeros in Python # Use the repeat function list_new = list(itertools.repeat(0, 10)) print(list_new) # Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The list function typecasts an object to a list.
The traditional approach of using a for
loop can also be used to create a list of zeros in Python. This method uses the list comprehension technique where a for
loop can create lists.
Method 3:
- Use the list comprehension technique to repeat zero in a list.
# Create a list of zeros in Python # Use the repeat function list_new = [0 for i in range(0, 10)] print(list_new) # Output: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
To conclude.
This particular article demonstrates several methods to create a list of zeros in Python. The main approach is to repeat this value in a list. This is achieved in the first method using the *
operator. Next, we use the itertools.repeat()
function to create a list of zeros. The last method shows the use of list comprehension to achieve the same.
Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.