1

Hello i have a code like this :

def remove_something (token):
    temp_token = token
    for t in token :
        if len(t) == 5:
            temp_token.remove(t)
    return temp_token
    
a = ['abcde','abcde','abcde','ef','ghi']
print(remove_something(a))

That output should be like this :

['ef', 'ghi']

But why like this ? :

['abcde', 'ef', 'ghi']

Dimas
  • 11
  • 2
  • 2
    `temp_token = token` doesn't make a copy of the list. You're removing from the same list you're iterating over. – Barmar Jun 10 '21 at 15:21
  • 1
    Why not use a list comprehension? `return [t for t in token if len(t) != 5]` – Barmar Jun 10 '21 at 15:23
  • Also this is a good explanation why: https://stackoverflow.com/a/6260097/8067109 – bca Jun 10 '21 at 15:30

3 Answers3

0

Use .copy() in order to make a copy of a certain variable. This way you can modify this copy without modifying the original variable.

def remove_something (token):
    temp_token = token.copy()
    for t in token :
        if len(t) == 5:
            temp_token.remove(t)
    return temp_token
    
a = ['abcde','abcde','abcde','ef','ghi']
print(remove_something(a))

output

['ef', 'ghi']
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
0

Use list comprehension instead:

a = ['abcde','abcde','abcde','ef','ghi']
b = [x for x in a if len(x) != 5]
print(b)
# ['ef', 'ghi']
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
0

Using List comprehension

  x = [token for token in a if len(token) != 5 ]
  print(x)

output
['ef', 'ghi']
Rima
  • 1,447
  • 1
  • 6
  • 12