antfuentes87
antfuentes87

Reputation: 897

How to use += (Add AND) with List Comprehension

I am trying to figure out how to use the code below with list comprehension.

link = 'page={}&index={}'
index = 10
links = []
for page in range(2, 4):
    links.append(link.format(page, index))
    index += 10

I have tried many different ways and Googled as much as possible (maybe I am not searching for the correct terms?). I am still unable to figure it out. Below is one of the ways I tried but I get a SyntaxError error.

link = 'page={}&index={}'
index = 10
links = [link.format(link, index) for page in range(2, 4) index += 10]

This should be the output of the list comprehension:

['page=2&index=10', 'page=3&index=20']

If anyone has any ideas it would be greatly appreciated it. Thank you!

Upvotes: 1

Views: 1353

Answers (2)

FHTMitchell
FHTMitchell

Reputation: 12156

You can't use += statements (or any statement for that matter) in a list comprehension. In your case, use zip and itertools.count:

import itertools
[link.format(page, index) for page, index in zip(range(2, 4), itertools.count(10, 10))]

Upvotes: 3

tobias_k
tobias_k

Reputation: 82929

You can use the enumerate: builtin function to increment the index:

>>> [link.format(page, i*10) for i, page in enumerate(range(2, 4), start=1)]
['page=2&index=10', 'page=3&index=20']

This will also work with any other iterable instead of just a range(2, 4), e.g. a list of strings. Any such iterable can thus be augmented with a counter variable, like index in your example.

Upvotes: 4

Related Questions