We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,996 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

"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
15 Hours
Discussion Span
4 Months Ago
Last Updated
6
Views
Question
Answered
UnchainedDjango
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

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)
hildisvini
Newbie Poster
1 post since Jan 2013
Reputation Points: 0
Solved Threads: 1
Skill Endorsements: 0

Even shorter ...

def toNums2(lst):
    return map(int, lst)
vegaseat
DaniWeb's Hypocrite
Moderator
6,475 posts since Oct 2004
Reputation Points: 1,447
Solved Threads: 1,611
Skill Endorsements: 36

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.

snippsat
Posting Shark
956 posts since Aug 2008
Reputation Points: 482
Solved Threads: 344
Skill Endorsements: 8

Thank you for all your help!

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

Quoted Text Here

UnchainedDjango
Newbie Poster
2 posts since Jan 2013
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 4 Months Ago by vegaseat, snippsat and hildisvini

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0687 seconds using 2.69MB