Home > Enterprise >  Best way to clear a each list in a nested list in Python?
Best way to clear a each list in a nested list in Python?

Time:07-01

Let's say I have a nested list like this

list_1 = [1, 2, 3]
list_2 = ["a", "b", "c"]
li = [list_1, list_2]

How do I clear each item in li so that list_1 and list_2 also become empty. I'm expecting something like:

print(li) # Output: [[],[]]
print(list_1) # Output: []
print(list_2) # Output: []

I tried

for i in range(len(parameters)):
        parameters[i] = []

but it doesn't clear list_1 and list_2

CodePudding user response:

You can use the list.clear method to empty the lists in-place and have that effect the original variables. By only assigning empty lists in their place, the original variables are not modified since you are creating new lists:

for p in parameters:
    p.clear()

which is equivalent to, but a better and more Pythonic version of:

for i in range(len(parameters)):
    parameters[i].clear()

CodePudding user response:

Is each list a fixed size? Inside the for loop use a while loop till it reaches the end of the list in each list.

x = len(list_1)
y = len(list_2)
i = list_1[0]

for i in range(len(list_1)):
    a = list_1[i]
    b = list_2[i]
    while i <= x and i <= y: #use and / or depending on the size of each list
          list_1.remove(a)
          list_2.remove(b)

print(li) 
print(list_1) 
print(list_2)

CodePudding user response:

You can use the clear method like so:

for i in li:
    i.clear()

Here is another way to do it with a nested for loop:

# Your lists
list_1 = [1, 2, 3]
list_2 = ["a", "b", "c"]
li = [list_1, list_2]

# The first for loop
for i in li: # This will look through every item in the list called "li"
    cop = i[:] # This will make a copy of the list
    # This is the second (or nested) for loop
    for j in cop: # This will go over every item in each nested list
        i.remove(j) # This will remove every item from that list
                
print(li) # Output: [[],[]]
print(list_1) # Output: []
print(list_2) # Output: []

Hope this helps :)

  • Related