MSey MSey - 4 months ago 48
Python Question

for statement in python

I'm confused about "x" in the python code below.

>>> # Grocery list
... grocery_list = ['apples', 'bananas', 'oranges', 'milk']
>>> for x in grocery_list:
... print(x, len(x))

I am confused about x's role in the for statement above. Is "x" a variable that is being defined within the for statement, or is it something else? It just seems different than how I am used to defining a variable, but I noticed "x" can be anything, which makes me think it is, in fact, a user-defined variable.

Please help.


Yes it's defined within the for statement. It's just a placeholder for an element in the list and can be called anything, e.g.

grocery_list = ['apples', 'bananas', 'oranges', 'milk']
for grocery in grocery_list:
  print(grocery, len(grocery))