"TypeError: not all arguments converted during string formatting" when trying to find even numbers

Question:

I am getting this error on Python 3, TypeError: not all arguments converted during string formatting. I know this is due to the string starting with "[" but the problem I’m solving has this as the input string '[1, 2, 3, 4, 5, 6, 7, 8, 9]' and the task is to find the even numbers on Python 3. Any help would be much appreciated.

def is_even_num(l):
  enum = []
  for n in l:
     if n % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))
TypeError: not all arguments converted during string formatting

If I try int(n), I get this error

ValueError: invalid literal for int() with base 10: '['

Edit 1:

A similar problem I am facing due to the input being a STRING

Python Exercise: Sort a tuple by its float element

price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]" 
print( sorted(price, key=lambda x: float(x[1]), reverse=True)) 
IndexError: string index out of range 

Here ‘Price’ is a string and the problem is to Sort a tuple by its float element

  1. Program to transpose a matrix using a nested loop

    y = "[[1,2,3,4],[4,5,6,7]]"
    result = [[0,0],
      [0,0],
      [0,0],
      [0,0]]
    
    #iterate through rows
    for i in range(len(X)):
    # iterate through columns
        for j in range(len(X[0])):
            result[j][i] = X[i][j]
    for r in result:
        print(r)
    
IndexError: list index out of range

I am getting this same type of problem again, the matrix has been input as a STRING.

Answers:

You pass your arguments as strings:

print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

Change that to:

print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

Output:

[2, 4, 6, 8]
Answered By: user12867493

You are not passing a list to your function, but a string. So the enumeration in your loop is going to enumerate the characters of your list, i.e. '[' then '1', then ',' etc.

That’s probably not what you want.

Use that call instead:

print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
Answered By: Chris

Remove [ and ] and split the string:

def is_even_num(l):
  enum = []
  for n in l.replace('[','').replace(']','').split(', '):
    if int(n) % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

Output:

['2', '4', '6', '8']

Another ellegant way is to use ast:

def is_even_num(l):
  enum = []
  for n in ast.literal_eval(l):
    if int(n) % 2 == 0:
       enum.append(n)
  return enum
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

Output:

['2', '4', '6', '8']

Also for you second part of your question as said before just use ast:

price = "[('item1', '12.20'), ('item2', '15.10'), ('item3', '24.5')]"  
price = ast.literal_eval(price) 
print( sorted(price, key=lambda x: float(x[1]), reverse=True))

Output:

[('item3', '24.5'), ('item2', '15.10'), ('item1', '12.20')]

Then:

y = "[[1,2,3,4],[4,5,6,7]]"
result = [[0,0],
 [0,0],
 [0,0],
 [0,0]]
X = ast.literal_eval(y)
#iterate through rows
for i in range(len(X)):
# iterate through columns
    for j in range(len(X[0])):
        result[j][i] = X[i][j]
for r in result:
  print(r)

Output:

[1, 4]
[2, 5]
[3, 6]
[4, 7]
Answered By: Code Pope

You can not use “%” operator with Strings. Remove those char from your string that can not be converted to int or float.

def is_even_num(l):
    l = l.replace('[','').replace(']','').split(",")
    return [x for x in l if int(x)%2 ==0]
print(is_even_num('[1, 2, 3, 4, 5, 6, 7, 8, 9]'))

This will return a list of even numbers.

Answered By: KUNAL KUMAR
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.