#1
  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. #2
  3. Commie Mutant Traitor
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Jun 2004
    Location
    Norcross, GA (again)
    Posts
    1,805
    Rep Power
    1570
    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])
    Rev First Speaker Schol-R-LEA;2 JAM LCF ELF KoR KCO BiWM TGIF
    #define KINSEY (rand() % 7) λ Scheme is the Red Pill
    Scheme in Short Understanding the C/C++ Preprocessor
    Taming Python A Highly Opinionated Review of Programming Languages for the Novice, v1.1

    FOR SALE: One ShapeSystem 2300 CMD, extensively modified for human use. Includes s/w for anthro, transgender, sex-appeal enhance, & Gillian Anderson and Jason D. Poit clone forms. Some wear. $4500 obo. tverres@et.ins.gov
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Location
    /dev/null
    Posts
    163
    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.

IMN logo majestic logo threadwatch logo seochat tools logo