1,105,333 Community Members

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

UnchainedDjango
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
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()
Member Avatar
hildisvini
Newbie Poster
1 post since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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)
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

Even shorter ...

def toNums2(lst):
    return map(int, lst)
Member Avatar
snippsat
Veteran Poster
1,039 posts since Aug 2008
Reputation Points: 483 [?]
Q&As Helped to Solve: 381 [?]
Skill Endorsements: 10 [?]
 
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.

UnchainedDjango
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
Unverified Member
 
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 vegaseat, snippsat and hildisvini
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: