Home > Mobile >  Python: how to shorten this loop?
Python: how to shorten this loop?

Time:11-01

The code seems a bit long for something that trivial.

Is there a pythonic way to shorten it?

fruit = None
for _fruit in basket:
  if _fruit['name'] != 'banana':
    continue
  fruit = _fruit

CodePudding user response:

fruit = None
for _fruit in basket:
    if _fruit['name'] == 'banana':
        fruit = _fruit

CodePudding user response:

Based on your initial conditions. Try this,

fruit, = [_fruit for _fruit in basket if _fruit['name'] == 'banana'][-1:] or (None, )

This allows:

  1. If there are multiple _fruits have name banana, assign the last one to fruit.
  2. If not, assign None to fruit.

CodePudding user response:

Assuming basket is a list:

fruit = [for x in basket if x != "banana"]

This also allows to have better performance due to comprehension list https://www.w3schools.com/python/python_lists_comprehension.asp

CodePudding user response:

If you want to have in minimum code lines

1) 
try: fruit = [b  for b in basket if b['name'] == 'banana'][0]
except: fruit = None

2) 
a = [b  for b in basket if b['name'] == 'banana']
fruit = a[0] if a else None

But a better way would be to stop the loop whenever it finds 'banana':

fruit = None
for b in basekt: 
    if b['name'] == 'banana': 
        fruit = b 
        break
  • Related