Search code examples
pythonlist-manipulation

Sum of only given index in a list with an another integer


I want to sum the particular index in this list

b = [3,4,6,8,9]
b[2:4] += 100
print(b)

When i try to execute i get:

b[2:4] += 100
TypeError: 'int' object is not iterable

The expected Output is:

[3,4,106,108,9]

Can anyone help me out to get me my expected output?


Solution

  • Use enumerate and list comprehension

    >>> b=[3,4,6,8,9]
    >>> [e*100 if i in range(2,4) else e for i,e in enumerate(b)]
    [3, 4, 600, 800, 9]