LoginSignup
1
1

Pythonの一行for文でbreakする方法

Last updated at Posted at 2024-03-18

Pythonって、よく一行でfor文を書いたりするのですが、breakが挟めないところを残念に思っていました。
が、違った!
次のコード、これの結果どうなるか知ってましたか?

class Test:
  def __init__(self, id, num):
    self.id = id
    self.num = num

  def get_id(self):
    self.num += 1
    return self.id

test_array = [
  Test(1, 10),
  Test(2, 20),
  Test(3, 30),
  Test(4, 40),
  Test(5, 50),
]

# IDが3のものを抽出したいとする
target = next(x for x in test_array if x.get_id() == 3)

# 余計なループは回したくないけど・・・実際のとこどうなのか確認
print([x.num for x in test_array])

私はこの結果が [11, 21, 31, 41, 51] になるものだと思っていました。
しかし、実際の結果は [11, 21, 31, 40, 50] になるのです。
すごく直感に反するので初めて知ったときは信じられませんでした。
しかし、これができるなら一行for文でbreakと同じことができるじゃないですか!
知ってる人は普通に知ってそうですが、とても感動したので残しておきます。

でわでわ

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1