Skip to main content
added third example
Source Link
Eli Courtwright
  • 194.6k
  • 69
  • 224
  • 257

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)] 

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = [] for tup in somelist: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) somelist = newlist 

Copying the list using remove might make your code look a little cleaner, as described in one of the answers below. You should definitely not do this for extremely large lists, since this involves first copying the entire list, and also performing an O(n) remove operation for each element being removed, making this an O(n^2) algorithm.

for tup in somelist[:]: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) 

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)] 

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = [] for tup in somelist: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) somelist = newlist 

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)] 

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = [] for tup in somelist: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) somelist = newlist 

Copying the list using remove might make your code look a little cleaner, as described in one of the answers below. You should definitely not do this for extremely large lists, since this involves first copying the entire list, and also performing an O(n) remove operation for each element being removed, making this an O(n^2) algorithm.

for tup in somelist[:]: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) 
Source Link
Eli Courtwright
  • 194.6k
  • 69
  • 224
  • 257

Your best approach for such an example would be a list comprehension

somelist = [tup for tup in somelist if determine(tup)] 

In cases where you're doing something more complex than calling a determine function, I prefer constructing a new list and simply appending to it as I go. For example

newlist = [] for tup in somelist: # lots of code here, possibly setting things up for calling determine if determine(tup): newlist.append(tup) somelist = newlist