I'm trying to learn python and I made this code to pratice. The objective is to read a list and if number is odd, another list receive it:
def purify(numlist): imp =  #list that receive the odd numbers for n in range(0,len(numlist[n])): #travel a list of numbers inputted by user if n % 2 != 0: #verify if number is pair or odd imp = numlist[n] #assigns odd numbers to the new list return imp #return list of odd numbers
But I'm receiving an error:
'int' object is not iterable
Can anyone help me? Thanks in advance!
If I keep your way of writing this function.
def purify(numlist): imp =  # numlist is iterable. range builtin would list all integers between 0 and the value. for n in numlist: # As pointed out in comments, the n variable will receive each number of the list iteratively. It is NOT the length of the list. if n % 2 != 0: # append method will add the element to the list. if you use assignemnt (=), # your variable imp will become an integer. imp.append(n) return imp
The more practical way to do is
imp = filter(lambda n: n % 2 != 0, numlist) # using a python built-in
imp = [n for n in numlist if n % 2 != 0] # using list comprehension