### Thread: Removes numbers smaller than four from a list?

1. No Profile Picture
Registered User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2013
Posts
5
Rep Power
0

#### Removes numbers smaller than four from a list?

This code is broken, and I can't figure out why. The loop only seems to be transversing half of the list. After playing around with it, it seems everything is find until afar the "if let < 4" statement. Can someone please help me fix this code (fix, not completely change) and explain to me whats wrong and what you did? Thanks

data = [2,2,2,2,2,4,2,4,2,4,2,4]
def myRemoveSmallNums(data):
""" Removes numbers smaller than four from the data """
index = 0
for elt in data:
if elt < 4:
data[index:index+1] = []
index += 1
myRemoveSmallNums(data)
2. Unfortunately, the approach you are taking won't work, as you are changing the data list while using it as the source for the elt objects. This is a problem because it disrupts the internal index in the for: loop.

To get the desired effect, you can do it in one of two ways. One is to simply modify your code so that you are building a new list inside the loop, then replacing the old list with the new one:

Code:
```data = [2,2,2,2,2,4,2,4,2,4,2,4]

def myRemoveSmallNums(data):
""" Removes numbers smaller than four from the data """
new_data = list()
for elt in data:
if elt >= 4:
new_data.append(elt)
return new_data

print (myRemoveSmallNums(data))```
The other approach is to use a list comprehension, which would filter the list in a single go, returning the new list.
Code:
`print([elt for elt in data if elt >= 4])`
3. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
May 2013
Location
/dev/null
Posts
164
Rep Power
19
Or you could use the filter function (apt for such purposes):
Code:
`new_data = filter(lambda x: x >= 4, data)`
That's in python 2.x; in 3.x filter function returns a filter object. So in python 3.x, it would be:

Code:
`new_data = list(filter(lambda x: x >= 4, data))`
Last edited by noobie1000; October 20th, 2013 at 11:57 AM.