(newbie)list conversion problem

Alan Kennedy alanmk at hotmail.com
Thu Jun 19 09:31:17 EDT 2003


Boris Genz wrote:

> I want to translate list of strings into identical list of integers. To
> clear things up, here is an example:
> I want this list: ['7659', '33', '454', '445'] to change in something
> like this: [7659, 33, 454, 445].
> I'm sure this is possible, and here is what I tried:
> x = ['7659', '33', '454', '445']
> for elements in x:
>   group = []
>   group.append(int(elements))

You were nearly right. There are a couple of small points to make

1. When you say "for elements in x", you may be slightly confused. It would be
better to say "for element in x" (no s), because "for" goes through the list one
entry at a time.

2. You should initialise the group list *before* you enter the for loop. The way
you have it now, your group list is reset to empty every time through the loop.

A version of your code that works is

x = ['7659', '33', '454', '445']
group = []
for element in x:
  group.append(int(element))

Another way to do it, using python "list comprehensions", introduced in python
2.0, is like this

group = [int(elem) for elem in x]

HTH,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list