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,156
  • 1
  • 20
  • 35

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
  • 107,498
  • 14
  • 145
  • 201
0

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

for element in list[:]:
       if element['title'] > 10:
          list.remove(element)
levi
  • 20,483
  • 7
  • 63
  • 71