greedIsGoodAha greedIsGoodAha - 2 months ago 15
Python Question

Is there an equivalent to the C++ pre/postfix operators for use in Python list comprehensions?

I writing a function which populates a list of lists of two elements, where the first element is an element from a different list and the second element is a value which increments.

def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[i, start++] for i in seq]


Is there an equivalent to the C++ postfix operators which can be used? Thanks!

Bonus question: Is it more Pythonic to use the list constructor, than to construct the list using square brackets?

Edit: Here is my current (less beautiful) workaround -

def list_of_pairs(seq, start):
""" Returns a list of pairs """
>>> list_of_pairs([3, 2, 1], 1)
[ [3, 1], [2, 2], [1, 3] ]
return [[seq[i], start+i] for i in range(len(seq))]

Answer

You may use enumerate() to achieve this. Enumerate return the index along with value while iterating over the list of values. And as per your requirement, you need list of list as [val, index + count]. Below is the sample code to achieve that:

>>> seq = [2, 6, 9]
>>> count = 2
>>> [[val, count+i] for i, val in enumerate(seq)]
[[2, 2], [6, 3], [9, 4]]