Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "x for x in" syntax mean? [duplicate]

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']
like image 390
Martin Melichar Avatar asked Nov 23 '17 22:11

Martin Melichar


People also ask

What does X for X in do?

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 .

What does X for X in Python mean?

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.

What is X in a for loop?

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.

What does for X do in Python?

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.


1 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.

like image 168
ninesalt Avatar answered Oct 12 '22 01:10

ninesalt