1

I'm new to python but not programming in general. Checking "Dive into Python" I have found this example (which works) but I don't get the syntax.

return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

Simply put, it's using variables k and v as strings for the "%s=%s" (nothing weird here) but those variables don't have any value yet. And just like that there is a for loop which iterates and assigns values to k and v. So this is what puzzles me: 1. The for loop is "returning" somehow values k and v to the previous statement (k,v). 2. Both statements (1. "%s=%s" % (k, v) and 2. for k, v in params.items()) can be in the same line with no syntax error.

I have checked the "for" syntax reference and it doesn't even hint in this direction, so I'm sure I have to check somewhere else, but don't know where.

Thank you in advance.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
vmstat
  • 13
  • 1
  • 3

2 Answers2

1
param.items() = [(key1, val1), (key2, val2) ... ]

Extended code for this list comprehension.. Generate the list inside the square brackets first, then join the list together by passing it to the join method.

new_list = []
for each_tuple in param.items():
    k = each_tuple(0)
    v = each_tuple(1)
    new_list.append("%s==%s" % (k, v,))
":".join(new_list)         # new_list = ['k1==v1', 'k2==v2', 'k3==v3',...]

>>> 'key1==value1:key2==value2:key3==value3....'
syntaxError
  • 896
  • 8
  • 15
1

List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

If you’re familiar with functional programming, you can think of list comprehensions as syntactic sugar for a filter followed by a map:

>>> doubled_odds = map(lambda n: n * 2, filter(lambda n: n % 2 == 1, numbers))
>>> doubled_odds = [n * 2 for n in numbers if n % 2 == 1]

Every list comprehension can be rewritten as a for loop but not every for loop can be rewritten as a list comprehension.

If you can rewrite your code to look just like this for loop, you can also rewrite it as a list comprehension:

new_things = []
for ITEM in old_things:
    if condition_based_on(ITEM):
        new_things.append("something with " + ITEM)

You can rewrite the above for loop as a list comprehension like this:

new_things = ["something with " + ITEM for ITEM in old_things if condition_based_on(ITEM)]    
zaidfazil
  • 9,017
  • 2
  • 24
  • 47