bhavesh sadhu
bhavesh sadhu

Reputation: 11

list index out of bound in Python

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

for i in range(len(arr_list)):
    sum=0
    sum += arr_list[i] + arr_list[i+1]
    print(sum)    

11 22 33 44 55

33 55 77 99

Traceback (most recent call last): File "abc.py", line 10, in sum += arr_list[i] + arr_list[i+1] IndexError: list index out of range Press any key to continue . . .

Upvotes: 1

Views: 142

Answers (4)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

This is a typical one-off-error. Functional programming (FP) reduces such occurrence a lot, and makes checks like len(lst) superfluous.

Here, you want to sum up two neighboring elements of the given list.

A typical idiom for this in pythonic FP is:

lst = [int(x) for x in input().split()]
[ x + y for x, y in zip(lst, lst[1:]) ]

# input: 11 22 33 44 55
# output: [33, 55, 77, 99]

The trick here is that with lst[1:] you generate lst shifted by 1. However, this is by 1 shorter than lst. The zip() pairs each element of lst with the corresponding in lst[1:]. The last element of lst has no corresponding partner. But zip ignores such pairings.

lst = [11, 22, 33, 44, 55]

zip(lst, lst[1:]) # generates from:

# lst       lst[1:]
#
# 11         22
# 22         33
# 33         44
# 44         55
# 55

# "zipping" to ->
[(11, 22),
 (22, 33),
 (33, 44),
 (44, 55)]
# (55, None) -> eliminated, zip stops where the shorter list
# stops
# however, zip() is in python also lazy (similar to map())
# its output is a generator.
# so when you want to inspect it, you have to do list(zip(...))
# to enforce its full execution, as with all generators...
#


# for x, y in [(11, 22), (22, 33), (33, 44), (44, 55)]
# loads each of the pair components on x and y
# and the expression at the beginning of the list-expression
# x + y  collects the sum of those.

Actually in functional terms it is a case for map(). However, in python, you have to enforce with list() the generator-like map().

lst = list(map(int, input().split()))
list(map(lambda x, y: x + y, lst, lst[1:])) 
# map processes the two lists in parallel similar to zip
# but gives the corresponding elements of each list
# directly to the arguments in the lambda expression/function:
# here to x and y.

11 22 33 44 55
## [33, 55, 77, 99]

So, by applying functional programming, you will be less exposed to such kind of errors.

Upvotes: 1

Giuseppe
Giuseppe

Reputation: 678

The problem is that in the last iteration you try to access an element that does not exist.

try with this:

target_sum = input()
arr_list = [int(x) for x in target_sum.split(" ")]

for i in range(len(arr_list)-1):
    sum = 0
    sum = arr_list[i] + arr_list[i+1]
    print(sum) 

If you want you can make a condition to check if the length of the list is bigger than 1:

target_sum = input()
arr_list = [int(x) for x in target_sum.split(" ")]

if len(arr_list) < 2:
    print("not enougth values")
    exit(0)

for i in range(len(arr_list)-1):
    sum = 0
    sum = arr_list[i] + arr_list[i+1]
    print(sum) 

if you want to print the result on a single line, you can add the end parameter to the print function like this:

for i in range(len(arr_list)-1):
    sum = 0
    sum = arr_list[i] + arr_list[i+1]
    print(sum, end=" ") 

Upvotes: 2

alec_djinn
alec_djinn

Reputation: 10789

The problem is arr_list[i+1], when you reach the last index i, it will look for i+1 which doesn't exist, thus the error.

There are a couple of workarounds:

1) decrease the range range(len(arr_list) -1)

2) use try/except:

for i in range(len(arr_list)):
    try:
        sum=0
        sum += arr_list[i] + arr_list[i+1]
        print(sum)
    except IndexError:
        pass

3) You can rethink your strategy. I, for example, would do something like this:

a = arr_list[:-1]
b = arr_list[1:]

for x,y in zip(a,b):
    print(x+y)

Also, mind that sum() is a Python function, it would be better to use another variable name.

Upvotes: 0

CypherX
CypherX

Reputation: 7353

The main problem was applying int() casting on input(), when your inputs were space separated values.

You can also perform the sum using a single-line of list-comprehension.

arr_list = [int(x) for x in input().split()]
target_sum = [a+b for a, b in zip(arr_list[0:-1], arr_list[1:])]

Example

target_sum = input() # 11 22 33 44 55
arr_list = [int(x) for x in target_sum.split()]
[a+b for a, b in zip(arr_list[0:-1], arr_list[1:])]
## Output
# [33, 55, 77, 99]

Upvotes: 0

Related Questions