1

My code for this returns 'None'. In case my question is not clear if i take the list [1 , 3 , 4 , 5 ,5 , 7], I want the list [1 , 3 , 4 , 7] to be returned. My code is as follows:

print("This program takes a list of 5 items and removes all elements of 5: ")

    list4 = []
    list4.append(input("Please enter item 1:"))  
    list4.append(input('Please enter item 2:'))  
    list4.append(input('Please enter item 3:'))  
    list4.append(input('Please enter item 4:'))
    list4.append(input('Please enter item 5:'))
    def remove_five():
        while 5 in list4:
            list4.remove(5)
    print(remove_five())
J.Sharpe
  • 11
  • 2

3 Answers3

2

Using list comprehension might come handy this time.

num_list = [1 , 3 , 4 , 5 ,5 , 7]
num_list = [int(n) for n in num_list if int(n)!=5]
print(num_list)

Output:

[1, 3, 4, 7]

N.B.: Use casting for string variables like below:

num_list = [int(n) for n in num_list if int(n)!=5]
arshovon
  • 13,270
  • 9
  • 51
  • 69
0

Your code prints None because your function has no return statement.

If you printed like so you'd see the list unchanged because you have no 5s in your list, you have '5' (a string)

remove_fives() 
print(list4) 

If you want to add integers, not strings, you need to cast it

append(int(input

If you want to create a list of no fives, try list comprehension

no_fives = [x for x in list4 if x!=5]

Or keeping the input as strings

no_fives = [x for x in list4 if x!='5']
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Change this:

def remove_five():
    while 5 in list4:
        list4.remove(5)

to this:

def remove_five():
    while '5' in list4:
        list4.remove('5')
    return list4
aghast
  • 14,785
  • 3
  • 24
  • 56