I have a list, let\'s say: list = [6,2,6,2,6,2,6]
, and I want it to create a new list with every other element multiplied by 2 and every other element multiplie
You can reconstruct the list with list comprehenstion and enumerate
function, like this
>>> [item * 2 if index % 2 == 0 else item for index, item in enumerate(lst)]
[12, 2, 12, 2, 12, 2, 12]
enumerate
function gives the current index of them item in the iterable and the current item, in each iteration. We then use the condition
item * 2 if index % 2 == 0 else item
to decide the actual value to be used. Here, if index % 2 == 0
then item * 2
will be used otherwise item
will be used as it is.