1

I am trying to make a list dynamic if a condition is met, not sure if it is entirely possible with python, especially with a list comprehension.

Here is my example code:

foobars = [
  {
    id: 1,
    bar: 'foo'
  }
]

all_foos = {
   foobar['id']: foobar['bar']  
   for foobar in foobars if condition == 'x' else foobars.pop(len(foorbars - 2))
}

Trying to make the list foobars dynamic by popping off the last two if a condition is met.

Essentially, I am trying to remove the last two list items if the django webpage renders in another country.

Open to suggestions and alternatives. Thanks.

Main issue is getting the conditional in the dict comprehension, not returning the last two items from the list.

code-demon
  • 11
  • 4

1 Answers1

0
forbars[:-2]

it will not change the actual data and will help you in displaying it without the last 2 elements, BTW the list has 1 element, so I think it would throw an error probably.

  • The main issue is adding the conditional statement in the dict comprehension, not necessarily getting the last to elements. – code-demon Aug 05 '21 at 16:43