Python) Add a list of different len

Asked 2 years ago, Updated 2 years ago, 15 views

I want to create a logic that adds two lists of different len's. I want to add list1=[1,2,3,4,5] and list2=[1,1,1,1,1,1,1] to make list3=[2,3,4,5,6,1,1]. But I keep getting errors ㅠ 혹시 Can you make the code easier than this?


lis1=[1,2,3,4,5] #len=5
list2=[1,1,1,1,1,1,1] #len=7
if len(list1)>len(list2):
    for i in range(len(list1)):
        list2.append(0) if list2[i]=[]
        list3[i]=list1[i]+list2[i]
else:
    for i in range(len(list2)):
        list1.append(o) if list1[i]=[]
        list3[i]=list1[i]+list2[i]
print(list3)

python

2022-09-21 23:06

1 Answers

list1=[1,2,3,4,5] #len=5
list2=[1,1,1,1,1,1,1] #len=7

if len(list2) > len(list1):
    for i in range(len(list1)):
        list2[i] = list2[i] + list1[i]

    print(list2)

else:
    for i in range(len(list2)):
        list1[i] = list1[i] + list2[i]

        print(list1)


Just add the element of the longest list to the element of the smallest list When the for statement ends, it will be simple if you print out a long list.

And the reason why the error occurs in the code is


2022-09-21 23:06

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.