0

I'm still learning Python and I was trying to do this:

#values is a list of string digits
values = int(i) for i in values

But it threw a Syntax error so after some googling I tried this:

values = [int(i) for i in values]

But I'm having a hard time understanding why one works and the other doesn't. Can you help me understand?

jarmod
  • 71,565
  • 16
  • 115
  • 122
MiguelP
  • 416
  • 2
  • 12
  • 4
    List comprehension is a specifically defined aspect of the python syntax. The reason it works with brackets is because that's how the python grammar is defined. A list comprehension is that specific case. Having the `int(i) for i in values` on its own doesn't make sense grammatically in python; there's no valid construct like that. It's only valid within brackets, by definition. – Random Davis Jun 09 '23 at 18:10

2 Answers2

2
values = int(i) for i in values

The above code with throw a syntax error because it is not correct Python syntax (for list comprehension). int(i) for i in values is a completely incorrect statement because there is no way Python knows how to combine, or construct, those 2 statements.

List comprehension statements are surounded by brackets [ ], because those are what enclose lists (I'm sure you know that [1, 2, 3] is a list).

values = [int(i) for i in values]

The above code uses list comprehension because it is surrounded by [ ]. The statement for i in values will go though the list called values, and one by one, assign a value to the variable I, for you to do something with. In this case, int(i) will convert the variable I and append, or add, to the values list. This line of code will in the end convert all the values in values to integers.

1

The type of brackets around the comprehension ends up determining the type of the resulting collection, be it a list [], set {}, or generator () (not to be confused with a tuple, which also uses parentheses)

All of the following are valid syntax, but the type of the result differs

# first, lets assume 'values' is a valid iterable...
values = range(10)

# list comprehension
values = [int(i) for i in values]
print(type(values))
# => <class 'list'>

# set comprehension
values = {int(i) for i in values}
print(type(values))
# => <class 'set'>

# generator comprehension
values = (int(i) for i in values)
print(type(values))
# => <class 'generator'>

Python also supports so-called "dictionary comprehensions" for creating dictionaries (key-values pairs) from two iterables (or a 2D list), but that's another answer for another question ;)

JRiggles
  • 4,847
  • 1
  • 12
  • 27