andrew
andrew

Reputation: 11

How to find the sum of first and last digit in a list

I want my program to allow the user to enter two lists of intergers, calculate the sum of first and last integers in each list and print the larger sum. At the moment it just outputs list2 twice.

list1 = []
list2 = []

n1 = [int(n) for n in input("List 1: ").split()]
list1.append(n1)
n2 = [int(n) for n in input("List 2: ").split()]
list2.append(n2)

s1 = 0
s2 = 0

s1 = list1[0] + list1[len(list1) - 1]
s2 = list2[0] + list2[len(list2) - 1]

if s1 > s2:
    print("Output: ", s1)
elif s1 < s2:
    print("Output: ", s2)
else:
    print("Output: Same")

This is what I get. I should be getting 12 as the Output.

List 1: 1 2 3 4 5
List 2: 5 6 7
Output:  [5, 6, 7, 5, 6, 7]

What am I doing wrong?

Upvotes: 1

Views: 2610

Answers (3)

K. Paul
K. Paul

Reputation: 9

# Take inputs from users
list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]

# SUM of first and last
sum1 = list1[0] + list1[-1]
sum2 = list2[0] + list2[-1]

# Checking
if sum1 > sum2:
    print("Output: ", sum1)
elif sum1 < sum2:
    print("Output: ", sum2)
else:
    print("Output: Same")

"""
OUTPUT:
-------------
List 1: 1 2 3
List 2: 4 5 6
Output:  10
"""

Upvotes: 0

nenadp
nenadp

Reputation: 816

You made a mistake: n1 is already a list, so your list1 becomes [[1,2,3,4,5]] - it has 1 element which is list of 5 elements. Same as for n2 and list2.

I rewrote your code, you can also use lst[-1] instead of lst[len(lst)-1]

list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]

s1 = list1[0] + list1[-1]
s2 = list2[0] + list2[-1]

if s1 > s2:
    print("Output: ", s1)
elif s1 < s2:
    print("Output: ", s2)
else:
    print("Output: Same")

Upvotes: 1

Nick is tired
Nick is tired

Reputation: 7056

append adds an element to a list, rather than merging 2 lists, so list1 and list2 have the values: [[1,2,3,4,5]] and [[5,6,7]] respectively, just use:

list1 = [int(n) for n in input("List 1: ").split()]
list2 = [int(n) for n in input("List 2: ").split()]

Alternatively, you can replace your calls of append with extend, which will concatenate the lists provided together.

Upvotes: 1

Related Questions