Python – Get 'i' variable assigned in if block

Question:

Hello I am trying to check some chars in a string. I found this code in the web. It works but I need to get i variable inside of the if block.

This is my code:

chars = set('qwertyuopasdfghjklizxcvbnm!"^+%&/()=?')

if any((i in chars) for i in myString):
   myIndex = myString.index(i)

But I’ve got this:

NameError: name 'i' is not defined
Asked By: Seminet

||

Answers:

walrus operator to the rescue !

if any(((i := x) in chars) for x in myString):
   myIndex = myString.index(i)

this assigns x to i outside the comprehension so it’s visible inside the block.

Answered By: Ahmed AEK
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.