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']
This gives x squared for each x in the specified range. In your example, the second x is the variable used by the for loop, and the first x is simply an expression, which happens in your case to be just x .
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.
x itself has no special meaning, it simply (as a part of the for loop) provides a way to repeat print random.randint(1,101) 10 times, regardless of the variable name (i.e., x could be, say, n ). In each iteration the value of x keeps increasing, but we don't use it.
This is used to truncate your list from the first element. And note that lists are mutable, if you find something like A[:] that means, they want to create a double of this list, without altering the original list, and use A[::-1] instead of reversed(A) to reverse the list. Dan D. Show activity on this post.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With