By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,957 Members | 2,038 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,957 IT Pros & Developers. It's quick & easy.

What is the fastest way to replace elements in list?

P: 3
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
Dec 2 '10 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 621
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.
Expand|Select|Wrap|Line Numbers
  1. a_list = [1, 2, -4, -3, 4, -9]
  2. b_list = []
  3.  
  4. for el in a_list:
  5.     if el < 0:
  6.         b_list.append(0)
  7.     else:
  8.         b_list.append(el)
  9. print b_list 
Dec 2 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.