0

I expect same result from these codes what wrong with the other one.

def remove_letters(list):
    x = []
    for i in range(len(list)):
        if type(list[i]) == type(1):
           x.append(list[i])
    print(x)
    return x
y = [1,'b', 'c',2]
remove_letters(y)
Output >> [1,2] 


def remove_letters(list):
    x = list
    for i in range(len(list)):
        if type(list[i]) == type('a'):
           x.remove(list[i])

    print(x)
    return x


y = [1,'b', 'c',2]
remove_letters(y)

output>> 

Traceback (most recent call last):
  File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 14, in <module>
    remove_letters(y)
  File "/Users/genesissales/PycharmProjects/1. Unbuquity [ 1, a, b, 2]/main.py", line 6, in remove_letters
    if type(list[i]) == type('a'):
IndexError: list index out of range

Process finished with exit code 1

its giving an error. it seems that list is also being change by the for loop.

genX
  • 1

1 Answers1

0

I have edited the code to make it more readable and pythonic.

from copy import copy
# don't use list as variable name, it's a reserved keyword
def remove_letters(l): # actually only keeps integers
    x = []
    for item in l:
        if isinstance(item, int):
           x.append(item)
    print(x)
    return x
y = [1,'b', 'c',2]
remove_letters(y)
#Output >> [1,2]

def remove_letters(l): # does remove all strings
    x = copy(l) # make a copy otherwise the y list from the outer scope is going to be altered! see https://stackoverflow.com/a/47264416/10875953
    for i, item in reversed(list(enumerate(x))): # iterate in reverse order that way it doesn't matter if we delete, enumerate adds the index
        if isinstance(item, str):
            x.remove(i)
    print(x)
    return x


y = [1,'b', 'c',2]
remove_letters(y)
Robin Dillen
  • 704
  • 5
  • 11