What is the fastest way to replace elements in list?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jacob l
    New Member
    • Dec 2010
    • 3

    What is the fastest way to replace elements in list?

    I am working with very large lists. I wish to replace elements satisfying a rule as quickly as possible.

    For Example:

    rule: if x < 0, replace with 0

    Mylist: [1, 2, -4, -3, 4, -9]

    Newlist: [1, 2, 0, 0, 4, 0]

    I have Mylist and want to get Newlist. My best guess is to use enumerate, but not sure how to write this appropriately. Thanks
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Generally, it is faster to append to a new list. Also, take a look at the Python Style Guide when you have time. There are coding conventions that make code easier to read and understand when someone posts.
    Code:
    a_list = [1, 2, -4, -3, 4, -9]
    b_list = []
    
    for el in a_list:
        if el < 0:
            b_list.append(0)
        else:
            b_list.append(el)
    print b_list

    Comment

    Working...