0

I have an array that looks like so:

data = [{'title':'10'},{'title':'15'},{'title':'25'},{'title':'6'},{'title':'4'}]

I want to iterate through the array while simultaneously removing elements that meet a certain criteria.

for element in data:
    if element['title'] > 10:
    # remove element from the array

Whats the best way to do this in python?

corycorycory
  • 1,448
  • 2
  • 23
  • 42

2 Answers2

2
data = [{'title':'10'},{'title':'15'},{'title':'25'},{'title':'6'},{'title':'4'}]

Using filter

>>> filter(lambda i : int(i['title']) <= 10, data)
[{'title': '10'}, {'title': '6'}, {'title': '4'}]

Using a list comprehension

>>> [i for i in data if int(i['title']) <= 10]
[{'title': '10'}, {'title': '6'}, {'title': '4'}]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

A simple way to do it. Notice the [:]

for element in list[:]:
       if element['title'] > 10:
          list.remove(element)
levi
  • 22,001
  • 7
  • 73
  • 74