0

How I can convert this code to one line?

target = 3
res = None
for x, y in [(1, 2), (3, 4), (5, 6)]:
    if x == target:
        res = y
        break

Surely I can use list comprehensive but it's doesn't have a break statement

I tried: this solution and a such code:

res = iter(lambda x=iter([(1, 2), (3, 4), (5, 6)]): next(x), (1, 2))
next(res)  # StopIteration

But both are failed

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
salius
  • 918
  • 1
  • 14
  • 30
  • 2
    You should look into https://docs.python.org/3/library/itertools.html. Or just not convert it to one line! – jonrsharpe Feb 14 '22 at 08:04
  • 1
    Your code mixes up `x` and `y` so I can't be sure what you meant, but it is something like `y_target = next((y for x, y in l if x == x_target), None)`. Please make sure you post [example] (with emphasis on being correct and reproducible) in the future. – Amadan Feb 14 '22 at 08:07
  • This is probably clearer as a for loop anyway. I would extract the for loop into a function, then call that function from your other code. (That makes it a one-liner from your other code. ;) – Jack Taylor Feb 14 '22 at 08:15
  • Sorry for mixing, I missed this. Now the code is edited. – salius Feb 14 '22 at 08:30
  • "Surely I can use list comprehensive" why would you want to? your code doesn't create a list, and is fine just like it is. List comprehensions do not have a break, they are for mapping/filtering operations – juanpa.arrivillaga Feb 14 '22 at 08:30
  • A oneliner, although doesn't break: `res = dict(reversed(pairs)).get(target)` – Kelly Bundy Feb 14 '22 at 08:42
  • 1
    You can try solution here - https://stackoverflow.com/a/2364277/9166673 – Shubhank Gupta Feb 14 '22 at 09:01

0 Answers0