Skip to content
Fix Code Error

Replace values in list using Python

March 13, 2021 by Code Error
Posted By: Anonymous

I have a list where I want to replace values with None where condition() returns True.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

For example, if condition checks bool(item%2) should return:

[None, 1, None, 3, None, 5, None, 7, None, 9, None]

What is the most efficient way to do this?

Solution

Build a new list with a list comprehension:

new_items = [x if x % 2 else None for x in items]

You can modify the original list in-place if you want, but it doesn’t actually save time:

items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
    if not (item % 2):
        items[index] = None

Here are (Python 3.6.3) timings demonstrating the non-timesave:

In [1]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: for index, item in enumerate(items):
   ...:     if not (item % 2):
   ...:         items[index] = None
   ...:
1.06 µs ± 33.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [2]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: new_items = [x if x % 2 else None for x in items]
   ...:
891 ns ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

And Python 2.7.6 timings:

In [1]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: for index, item in enumerate(items):
   ...:     if not (item % 2):
   ...:         items[index] = None
   ...: 
1000000 loops, best of 3: 1.27 µs per loop
In [2]: %%timeit
   ...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   ...: new_items = [x if x % 2 else None for x in items]
   ...: 
1000000 loops, best of 3: 1.14 µs per loop
Answered By: Anonymous

Related Articles

  • Combining items using XSLT Transform
  • Can't install via pip because of egg_info error
  • Convert array to nested JSON object - Angular Material tree
  • What's the difference between eval, exec, and compile?
  • How to add 'load more' functionality to items on a…
  • Centering in CSS Grid
  • LNK2019 símbolo externo public: bool __thiscall ……
  • How do I merge two dictionaries in a single…
  • Changing Icon Color behind ListTile in an…
  • Display Grid does not work in Polymer correctly
  • How to show title in hover - css / jquery
  • HashSet vs. List performance
  • How to update Python?
  • Best way to replace multiple characters in a string?
  • How to make vuetify navigation drawer to close group…
  • in doesn't call method on item change
  • In CSS Flexbox, why are there no "justify-items" and…
  • How do I include certain conditions in SQL Count
  • Smart way to truncate long strings
  • Install pip in docker
  • Objective-C : BOOL vs bool
  • How to specify line breaks in a multi-line flexbox layout?
  • How the int.TryParse actually works
  • SwiftUI View Not Updating on Button Toggle After…
  • How to map and remove nil values in Ruby
  • Usage of __slots__?
  • Dart core element core-collapse
  • Check for internet connection with Swift
  • Valid values for android:fontFamily and what they map to?
  • Truth value of a Series is ambiguous. Use a.empty,…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • AppCompat v7 r21 returning error in values.xml?
  • C++ template,typename and operator
  • How to make Vue reactive content update quickly?
  • Best way to Receive Consecutives Input calls?
  • How to filter a RecyclerView with a SearchView
  • Could std::vector::iterator implement its deref…
  • How to create ranges and synonym constants in C#?
  • Remix error The transaction has been reverted to the…
  • Polymer 1.0: Sorting iron-list
  • Show only certain items at certain condition on…
  • How to add Css Class to item inside Ember's…
  • Perfomance issues with large number of elements in…
  • Vuetify 2.2 DataTable multiple filters
  • backbone model save issue
  • v-for, how to open clicked List Item
  • I do not use TBB, but I get linker errors related to TBB
  • Pandas - Merge rows of dataframe that have a shared value
  • Route's Model Hook with Ember Data "filter" not…
  • Running parallel async tasks and return result in…
  • How to do date/time comparison
  • Fastest way to list all primes below N
  • Change the background color of a list item in Vuetify
  • Polymer 1.x: Two-way databinding for paper-dropdown-menu
  • After a little scroll, the sticky navbar just is not…
  • Are dictionaries ordered in Python 3.6+?
  • Convert True/False value read from file to boolean
  • How to delete an item in a list if it exists?
  • What's the difference between Instant and LocalDateTime?
  • Change Array Order in Aurelia, weird behaviour
  • How to convert string to expression ( value ) in…
  • Styling active-class in Vuetify
  • Chrome / Safari not filling 100% height of flex parent
  • Relative imports for the billionth time
  • how to Display Tuple{Float64, Bool}
  • Best way to notify polymer of updates to list items
  • How can I get the data with using url parameter in a…
  • Error inflating class…
  • Does moment.js allow me to derive a timezone…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • Ember Data nested Models
  • center 3 items on 2 lines
  • data.table vs dplyr: can one do something well the…
  • How to force binding re-evaluate or re-rendering in Aurelia
  • Backbone Validate is sending a request when validation fails
  • What are type hints in Python 3.5?
  • Keras Sequential API is replacing every layer with…
  • Polymer Dom-Repeat Binding to Content
  • Vuetify Item group how to preselect item?
  • functions calls inside dom-repeat only executed once
  • Polymer paper-dropdown-menu not rendered correctly…
  • Vuetify v-list-item style change on hover
  • How to change the floating label color of TextInputLayout
  • Equals implementation with override Equals,…
  • What does "Fatal error: Unexpectedly found nil while…
  • Reference - What does this regex mean?
  • List comprehension vs. lambda + filter
  • Start redis-server with config file
  • Why does C++ code for testing the Collatz conjecture…
  • Manually raising (throwing) an exception in Python
  • Polymer nested dom-repeat templates are not updating…
  • Python Dictionary Comprehension
  • How do I output an opening or closing tag in an…
  • Default Param on Polymer.js Input Range
  • Git - Pushing code to two remotes
  • What does Ruby have that Python doesn't, and vice versa?
  • Observe property on an array of objects for any changes
  • Vuetify How to open and close dialogs within a data table
  • Generating a drop down list of timezones with PHP
  • Add a popup modal to vuetify vue.js

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I make text bold in HTML?

Next Post:

Redirect stderr and stdout in Bash

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error