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
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.
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
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.