How to clear list in python

Different ways to clear a list in Python

Clearing up all the elements in a python list can be done in many ways. Below are the some of the methods which are implemented to achieve this.

using clear()

This function is a part of standard library and empties the python list completely.

Syntax: list_name.clear() list_name is the name of the list supplied by

Example

In the below example we take a list and apply the clear (). The result is an empty list.

list = ['Mon', 'Tue', 'Wed', 'Thu'] print("Existing list\n",list) #clear the list list.clear() print("After clearing the list\n") print(list)

Output

Running the above code gives us the following result −

Existing list ['Mon', 'Tue', 'Wed', 'Thu'] After clearing the list []

Using del()

The del() function you can selectively remove items at a given index or you can also remove all the elements, making the list empty.

In the below example we take a list, remove the element at index 2. Then we remove all the elements.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu'] print("Existing list\n",list) #deleting one element from the list del list[2] print("After deleting an element\n") print(list) # Removing all elements del list[:] print("After deleting all elements\n") print(list)

Output

Running the above code gives us the following result −

Existing list ['Mon', 'Tue', 'Wed', 'Thu'] After deleting an element ['Mon', 'Tue', 'Thu'] After deleting all elements []

Using *=0

In this approach we just assign 0 to all elements in the list which makes the list empty. The * is a character representing all elements.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu'] print("Existing list\n",list) # Removing all elements list *= 0 print("After deleting all elements\n") print(list)

Output

Running the above code gives us the following result −

Existing list ['Mon', 'Tue', 'Wed', 'Thu'] After deleting all elements []

List Re-Initialization

We can re-initialize a list by just assigning an empty list to it. In the below example we take a list and then assign an empty list to it which creates an empty list.

Example

list = ['Mon', 'Tue', 'Wed', 'Thu'] print("Existing list\n",list) # Removing all elements list = [] print("After deleting all elements\n") print(list)

Output

Running the above code gives us the following result −

Existing list ['Mon', 'Tue', 'Wed', 'Thu'] After deleting all elements []

Источник

How to Clear a Python List [4 Ways & Examples]

Python list is a common data type used to store multiple values for easy access. Sometimes, you may want to clear Python lists either by removing all the elements or removing elements one by one.

Читайте также:  Html default file association

This is a comprehensive guide to clearing a list in Python in 4 different ways.

The short answer: To clear the whole list in Python, use the list.clear() method.

For example, let’s wipe out a list of numbers:

numbers = [1, 2, 3, 4, 5] numbers.clear() print(numbers)

To remove an item at a specific index, use the list.pop(index) method.

For example, let’s remove the second element of a list:

nums = [1,2,3] nums.pop(1) print(nums)

All in all, there are four ways to remove elements from a list in Python:

Let’s go through each of these.

1. Clear() in Python

Clear a list in Python using the list.clear() method.

To completely clear a list in Python, use the built-in clear() method. This removes all the elements of the original list.

numbers = [1, 2, 3, 4, 5] numbers.clear() print(numbers)

Now there are no longer values in this list.

Notice that this is not always what you want. Sometimes you only want to get rid of particular elements of the list. The rest of this guide focuses on removing particular elements rather than wiping out the entire list.

2. Pop() Method in Python

Clearing a list using the pop() method in Python

You can remove a single element with a specific index using the list’s pop() method.

To do this, pass the index of the item you want to remove as an argument. (And keep in mind that Python indexing starts at 0):

For example, let’s remove the second number from a list of numbers:

numbers = [1,2,3] numbers.pop(1) print(numbers)

Notice the pop() method also returns the removed value. If you need to store it somewhere, you don’t need to do it separately.

3. Remove() Method in Python

Remove the first occurrence of an element in a list with the remove method.

Another way to remove elements from a list is by using the list.remove() method to remove the first occurrence of a particular element from the list. To do this, pass the element you want to remove into the method.

For instance, let’s remove the first occurrence of the number 2 in the list of numbers:

nums = [1,1,2,2,3,3] nums.remove(2) print(nums)

4. The del Statement in Python

Clearing a Python list with the del statement.

Last but not least, you can also remove elements from a list using the del statement.

To do this specify the index of the element you wish to remove.

For example, let’s remove the first element of a list of numbers:

nums = [1,2,3] del nums[0] print(nums)

In contrast to the pop() method you saw earlier, the del statement only deletes the element and does not return it.

Conclusion

  • To clear a whole Python list, use the clear() method of a list.
  • To remove an element at a specific index, use the pop() method or the del statement.
  • To remove the first occurrence of an element in a list, use the remove() method.

Источник

4 Ways to Clear a Python List

Python Clear List Cover Image

In this tutorial, you’ll learn four different ways to use Python to clear a list. You’ll learn how to use the clear method, the del statement, the *= operator, and list item re-assignment. Knowing how to clear a list is a task that should seem easy, but is an often elusive skill. After reading this tutorial, you’ll have learned four different ways to clear a Python list in order to start fresh.

Читайте также:  My java won work

The Quick Answer: Use clear

Quick Answer - Python Clear List

What are Python Lists?

Lists in Python are one of the main data structures that exist in the language. They have some unique attributes, similar to arrays in other languages. They can hold values of different data types, meaning that they’re heterogeneous. They are also ordered, meaning that you can access the items by their index position. Python list indices start at 0 and increment by 1. Python lists can also contain duplicate values.

How does Python List Indexing Work

In the next section, you’ll learn how to clear a Python list with the .clear() method.

Clear a Python List with Clear

One of the easiest ways to clear a Python list is to the use the list.clear() method. The method empties a given list and doesn’t return any items. The method was introduced in Python 3.2, so if you’re using an earlier version, you’ll need to read on to learn how to use the del operator.

Let’s see how we can empty a list by using the clear method:

# Clear a Python List with .clear() items = ['datagy', 1, 2, 3] items.clear() print(items) # Returns: []

Let’s break down what we did above:

  1. We instantiated a list
  2. We then applied the clear method to empty the list
  3. We print the list to ensure that the list is emptied

Now that we know how to use the clear method, we can explore some additional properties about it. The method doesn’t accept any arguments and it modifies a list in place (meaning that we don’t re-assign it to another list).

In the next section, you’ll learn how to empty a Python list with the del keyword.

Want to learn how to pretty print a JSON file using Python? Learn three different methods to accomplish this using this in-depth tutorial here.

Clear a Python List with del

The Python del keyword allows us to delete a particular list item or a range of list items at particular indices. If you want to learn how to use the Python del keyword to delete list items, check out my in-depth tutorial here. Since we can use the Python del keyword to delete items or ranges of items in a list, we can simply delete all items in the list using the : operator.

Let’s see how we can use the del keyword to empty a Python list:

# Clear a Python List with del items = ['datagy', 1, 2, 3] del items[:] print(items) # Returns: []

Let’s break down what we did here:

  1. We instantiated a Python list, items
  2. We then used the del keyword to delete items from the first to the last index
  3. We then printed the list to make sure it was empty
Читайте также:  Java convert string to long type

Interestingly, the .clear() method works exactly the same as the del [:] keyword, under the hood. It really just represents syntactical sugar in order to make the process a little easier to understand.

In the next section, you’ll learn how to empty a Python list using the *= operator.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

Clear a Python List with the *= Operator

Python allows us to chain operators together. For example, writing a = a + 1 is the same as writing a += 1 . Another way to chain operators is to use the *= , which reassigns the variable multiplied by zero. When we apply this operator a list, we assign the value of 0 to each item, thereby removing the items from the list.

Let’s see how we can use the *= operator to empty a Python list of all of its elements:

# Clear a Python List with *= items = ['datagy', 1, 2, 3] items *= 0 print(items) # Returns: []

In the next section, you’ll learn how to use Python to empty a list using list item re-assignment.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Clear a Python List with List Item Re-assignment

While it may seem intuitive to empty a list simply by writing some_list = [] . This approach doesn’t actually delete the items from the list, it just removes the reference to the items. If the list has also been assigned to another variable, it’ll be retained in memory.

We can, however, assign the full range of items to be empty items. This will delete all of the items in a list, thereby clearing it.

Let’s see how we can do this with Python:

# Clear a Python List with *= items = ['datagy', 1, 2, 3] items[:] = [] print(items) # Returns: []

In the example above, we can see that we re-assigned all of the list items by using the list indexing method. We were able to access all of the items and assign them an empty value.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Conclusion

In this tutorial, you learned four different ways to use Python to clear a list. You learned how to use the .clear() method, the del keyword, the *= operator, and list item re-assignment. Being able to work with lists in different ways is an important skill for a Pythonista of any level.

To learn more about Python lists, check out the official documentation here.

Источник

Оцените статью