kira.99
kira.99

Reputation: 41

I am facing this error in python "not all arguments converted during string formatting" while writing a code for converting two list within one list

In this code specifically I am getting error while using modulus with 'i'.

def fun(l):
    even=[]
    odd=[]
    for i in l:
        if i % 2 == 0:
            even.append(i)
        else:  
            odd.append(i)  

    total=[]
    total.append(odd,even)        
    return total

numbers=['2','3','4','5','7'] 
print(fun(numbers))

ERROR:

File "e:\python codes\lists\ex4.py", line 14, in <module>
    print(fun(numbers))
  File "e:\python codes\lists\ex4.py", line 5, in fun
    if i % 2 == 0:
TypeError: not all arguments converted during string formatting

Upvotes: 2

Views: 162

Answers (3)

Kemp
Kemp

Reputation: 3649

You are passing in a list of strings instead of a list of numbers. When you apply the % operator to a string it performs string formatting. What you probably wanted to do was

numbers=[2,3,4,5,7] 

Additionally your line

total.append(odd,even) 

will give an error as append only takes a single argument.

Upvotes: 2

zwitsch
zwitsch

Reputation: 359

As mentioned, you would want to use a list of integers instead of strings. Then append takes only one parameter instead of two.

Splitting

 total.append(odd, even)

into

 total.append(odd)        
 total.append(even)

will give the desired result: [[3, 5, 7], [2, 4]].

Upvotes: 0

user16527495
user16527495

Reputation:

Your arguments in your list are currently strings, so they're being treated as strings instead of integers.

You have two options:

    1. change the input to integers as follows:

numbers = [2, 3, 4, 5, 7]

    1. convert your strings within your function:
def fun(l): 
   ...
   for i in l:
      if type(i) == str:
         if int(i) % 2 == 0:
         ...
      else:
           i % 2 == 0:
           ...
      ...

The second method could lead to various problems with mutation, and also doesn't have very good readability. I would go with the first.

Also, make sure to use: total = [even, odd]

Upvotes: 0

Related Questions