40

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']
cs95
  • 330,695
  • 80
  • 606
  • 657
Martin Melichar
  • 850
  • 1
  • 9
  • 14
  • 6
    `[x for x in text if x.isdigit()]` is a "list comprehension". It means something like "for each x in text, if x.isdigit() is True, add it to the list" – Blorgbeard Nov 23 '17 at 22:54

1 Answers1

30

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.

JohnEye
  • 5,959
  • 4
  • 33
  • 64
ninesalt
  • 3,446
  • 4
  • 27
  • 65