Mass17
Mass17

Reputation: 1605

How to append the list in Python for certain index?

I have a list like this;

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1] # list of 9 elements

I want to have another list2 like this..

list2 = [1, 2, 2, 2, 2, 2, 2, 2, 2, 1] # list of 10 elements

list2 is formed by keeping 0th element & the 8th element from list1 & adding adjacent elements next to each other in list1. This is what I did;

list2 = [None] * 10
list2[0] = list2[9] = 1

for idx, i in enumerate(list1):
    try:
        add = list1[idx] + list1[idx+1]
        #print(add) 
        list2[1:9].append(add)
    except:
        pass

print(list2)

But I am not getting the desired output... actually the list2 is not updating, I am getting:

[1, None, None, None, None, None, None, None, None, 1]

Upvotes: 2

Views: 3404

Answers (3)

user3064538
user3064538

Reputation:

Similar to the other answers but I would do it in two lines of code using an intermediate list (or just modify the original list if you won't need it anymore) to make the padding easier to see:

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

lyst = [0, *list1, 0]
list2 = [prev + cur for prev, cur in zip(lyst, lyst[1:])]

print(list2)

Upvotes: 2

Nick
Nick

Reputation: 147206

An alternate way to achieve your desired result is to effectively shift list1 by prepending a list with one entry of 0 to it, and then add it to itself (extended by an entry of 0 to match lengths), by using zip to create a list of tuples that can be iterated over:

list1 = [1, 1, 1, 1, 1, 1, 1, 1, 1]

list2 = [x + y for x, y in zip([0] + list1, list1 + [0])]
print(list2)

Output

[1, 2, 2, 2, 2, 2, 2, 2, 2, 1]

Upvotes: 4

norok2
norok2

Reputation: 26896

What about something like:

list2 = list1[:1] + [x + y for x, y in zip(list1[0:], list1[1:])] + list1[-1:]

Upvotes: 1

Related Questions