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()
4
Contributors
4
Replies
6
Views
4 Years
Discussion Span
Last Post by UnchainedDjango
Featured Replies
  • 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: … Read More

  • 2

    Even shorter ... def toNums2(lst): return map(int, lst) Read More

  • 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 … Read More

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)

Edited by hildisvini

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.

Edited by snippsat

0

Thank you for all your help!

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

Quoted Text Here

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.