55

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
  • 379,657
  • 97
  • 704
  • 746
Martin Melichar
  • 1,036
  • 2
  • 10
  • 14
  • 11
    `[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

43

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
  • 6,436
  • 4
  • 41
  • 67
ninesalt
  • 4,054
  • 5
  • 35
  • 75