david_10001
david_10001

Reputation: 492

How to make a variable equal to a list with items removed, without changing original list?

I have tried to remove remove items from a list and then make it equal to another variable while still keeping the original list.

Code:

print (len(desc1))
desc2 = []
for tuple in desc1:
    for line in tuple:
        if line.endswith(':'):
            desc2 = desc1.remove(tuple)
print (len(desc1))
print (desc2)

Output:

550 
200
None

What I would like the output to be:

550
550
200

What do I have to use to achieve this?

Upvotes: 0

Views: 36

Answers (1)

Adam Smith
Adam Smith

Reputation: 54213

Copy the list first.

desc2 = desc1[:]  # shallow copy
for tuple in desc2:
    for line in tuple:
        if line.endswith(":"):
            desc2.remove(tuple)  # don't assign here

Note that this is kind of a bad idea anyhow, since you're mutating the list (removing members) as you're iterating over it. In addition, you're using list.remove hundreds of times, and it's not exactly quick. Instead consider using a list comprehension.

desc2 = [tup for tup in desc1 if not any(line.endswith(":") for line in tup)]
# or
desc2 = filter(lambda t: not any(line.endswith(":") for line in t), desc1)

Upvotes: 1

Related Questions