1.11M Members

Modifies each entry in the list by converting it to a number

 
0
 

"toNumbers(strList) is a list of things,each of which represents a number.Modifies each entry in the list by converting it to a number."

Here is my code and it won't work,please help,thank you!

import string
def toNumbers(strList):
    nums = []
    for i in strList:
        nums = nums.append(int(i))
    return nums
def main():
    m = ["1","2"]
    print toNumbers(m)
main()
 
2
 

You're trying to assign a function call 'nums.append(x)' which has a 'None' value to the variable 'nums'. Therefore you can't apply the 'append'-method to a None-value.
You should just apply the append-method to your list instead:

def toNumbers(strList):
        nums = []
        for i in strList:
            nums.append(int(i))
        return nums

or shorter:

def toNums(lst):
    return map(lambda x: int(x), lst)
 
2
 

Even shorter ...

def toNums2(lst):
    return map(int, lst)
 
2
 

The functional programming way with map() is short and fine for this.
In Python are list comprehension used much and in many cases more prefered than a functional style.

def to_numbers(str_list):
    return [int(i) for i in str_list]

lst = ['1', '2']
print to_numbers(lst)

If you wonder why i have changed to small letter and use _,look at PEP-8.

 
0
 

Thank you for all your help!

I made a STUPID mistake! And now I see it.

Quoted Text Here

Question Answered as of 1 Year Ago by hildisvini, vegaseat and snippsat
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: