Home > OS >  print all the list elements with an even index number, error statement
print all the list elements with an even index number, error statement

Time:10-28

for my task, which I think I have already right, but on Snakify it shows me this error statement: Traceback (most recent call last): ValueError: invalid literal for int() with base 10: '1 2 3 4 5' On google colab this error doesn't show up, on snakify it does, but I need this error to go so I can check my solutions. Any suggestions?

Task is: a list of numbers, find and print all the list elements with an even index number.

a = []
b = []

numbers = input()
for n in numbers.split():
    a.append(int(n))

    if int(n) % 2 == 0:
      b.append(a[int(n)])

print(b)

CodePudding user response:

int(input()) will only work on a single number. If you want to enter many numbers at once, you'll have to call input() first, split it into separate numbers, and call int() on each one:

numbers = input()
for n in numbers.split():
    a.append(int(n))

Or using a list comprehension:

numbers = input()
a = [int(n) for n in numbers.split()]

CodePudding user response:

int() can convert only numbers and raise error if argument contain a non-digit char, for example space ' '. You can use:

nums = input().split()  # split() method splited string by spaces
a = []
for i in range(len(nums)):  # len() function return count of list elements
    if (i % 2) == 0:
        a.append(nums[i])

print(a)

Also you can get IndexError: list index out of range Please comment if interesting why

  • Related