The Python Oracle

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

This video explains
What does the "x for x in" syntax mean?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2

--

Chapters
00:00 Question
00:41 Accepted answer (Score 36)
01:07 Thank you

--

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

Accepted answer links:
[this]: https://web.archive.org/web/201803090538...

--

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)