Remove Even Numbers From A List
How can I remove even numbers from a list? a = [] i = 0 while i < 10: c = int(raw_input('Enter an integer: ')) a.append(c) i += 1 # this is the same as i = i +
Solution 1:
Why not preventing the append if the number is even, instead of adding and then checking for removal?
a = []
counter = 0
while counter < 10:
c = int(raw_input('Enter an integer: '))
if c % 2 != 0:
a.append(c)
counter += 1print(a)
Solution 2:
i
is reassigned by the for
statement. Use a different variable.
Solution 3:
If you want to see how to 'filter' a list according to a predicate, here is an example:
a_without_even = filter(lambda x: x%2==1, a)
Solution 4:
def removalDiffMethod(self, array):
l=0
r=len(array)
while l<r:
ifarray[l]%2==0:
array[l:r] = array[l+1:r+1]
r-=1else:
l+=1returnarray[:r]
Solution 5:
Something like this?
your_dirty_list = [2,3,3,3,4,4,2,2,7,7,8]
your_clean_list = [clean_dude for clean_dude in your_dirty_list if clean_dude % 2]
Out[]: [3, 3, 3, 7, 7]
Post a Comment for "Remove Even Numbers From A List"