The Python Oracle

What does the "x for x in" syntax mean?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 What Does The &Quot;X For X In&Quot; Syntax Mean?
00:33 Accepted Answer Score 45
00:57 Thank you

--

Full question
https://stackoverflow.com/questions/4746...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #forloop

#avk47



ACCEPTED ANSWER

Score 45


This is just standard Python list comprehension. It's a different way of writing a longer for loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.

See this for more info on list comprehension.

Using a for loop, you would get the same result with:

numbers = []
for x in text:
    if x.isdigit():
        numbers.append(x)