Multiplication of every second number in the list

I need to be able to multiply every second number in the list by 2, so say:

List = [1,2,3,4]

I want this to return [1,4,3,8], but all the ways I tried, for example

credit_card = [int(x) for x in input().split()]

credit_card[::2] = [x*2 for x in credit_card[::2]]

print(credit_card)

If I enter the same list from before it returns [2,2,6,4]

Is there a way to accomplish what I'm trying to accomplish?

+4
source share
6 answers

You are almost there, you just need to start with the second (1-indexed) element:

credit_card[1::2] = [x*2 for x in credit_card[1::2]]

However, since you seem to be using the Lunh checksum , you only need the sum of these digits without the need to update the source data, as done in this example .

+4
source
lst = [1,2,3,4]

new_lst = [2*n if i%2 else n for i,n in enumerate(lst)]     # => [1, 4, 3, 8]
+1
credit_card = input().split()
for x in len(credit_card)
    if x % 2 != 0
        credit_card[x] = credit_card[x] * 2

print (credit_card)
0

, :

[i* 2 if p % 2 else i for p, i in enumerate(l)]

where i is the element p-th l .

0
source
for i,_ in enumerate(credit_card):
    if i%2:
        credit_card[i] *= 2

or if you want to be fantastic:

 credit_card=[credit_card[i]*(2**(i%2)) for i in range(len(credit_card))]
0
source
>>> l = [1,2,3,4]
>>> 
>>> list(map(lambda x: x*2 if l.index(x)%2 else x, l))
[1, 4, 3, 8]
0
source

Source: https://habr.com/ru/post/1628137/


All Articles