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

Question:

What actually happens when this code is executed:

text = "word1anotherword23nextone456lastone333"
numbers = [x for x in text if x.isdigit()]
print(numbers)

I understand, that [] makes a list, .isdigit() checks for True or False if an element of string (text) is a number. However I am unsure about other steps, especially: what does that “x” do in front of for loop?

I know what the output is (below), but how is it done?

Output: ['1', '2', '3', '4', '5', '6', '3', '3', '3']
Asked By: Martin Melichar

||

Answers:

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.

Answered By: ninesalt
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.