On 04/05/13 14:13, Jim Mooney wrote:
I'm turning an integer into a string so I can make a list of separate
chars, then turn those chars back into individual ints, but the
resulting list still looks like string chars when I print it. What am
I doing wrong?

listOfNumChars = list(str(intNum))

This creates a list of characters.


for num in listOfNumChars:
     num = int(num)

This walks over the list, setting the variable "num" to each character in turn, then inside 
the loop you set the variable "num" to the converted char->int. But num isn't linked to 
the list in any way -- num has no memory that the value it got came from a list. Reassigning num 
inside the loop doesn't touch the list in any way, so naturally the list doesn't change.


print(listOfNumChars)

# result of 455 entered is ['4', '5', '5']


To split a number into digits, the shortest way is to use a list comprehension:


digits = [int(c) for c in str(num)]


We can expand that list comp into a for-loop:


digits = []
for c in str(num):
    digits.append(int(c))



Notice that there is no need to convert the string into a list. You can iterate 
over the characters of a string just fine.

If you prefer to create a list, then modify it in place, we can do this:


digits = list(str(num))
for position, char in enumerate(digits):
    digits[position] = int(char)



Here we use enumerate() to iterate over pairs of (position, value) instead of 
just value:

py> list("abcd")
['a', 'b', 'c', 'd']
py> list(enumerate("abcd"))
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]



Here's another way, using map:


digits = map(int, str(num))  # Python 2.x only

digits = list(map(int, str(num)))  # Python 3.x or better



Why the difference between Python 2.x and 3.x? In 2.x, map is "eager", it runs all the 
way through the string as soon as you call it, returning a list. In 3.x, map is "lazy", 
and only generates values when and as needed. By wrapping the map generator in a call to list, that 
forces it to run all the way through the string.



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to