Bob_94
Bob_94

Reputation: 2845

Change the type in a Python list?

Is there a Pythonic way to change the type of every object in a list?

For example, I have a list of objects Queries. Is there a fancy way to change that list to a list of strings?

e.g.

lst = [<Queries: abc>, <Queries: def>]

would be changed to

lst = ['abc', 'def']

When str() is used on a Queries object, the strings I get are the ones in the second code sample above, which is what I would like.

Or do I just have to loop through the list?

Many thanks for any advice.

Upvotes: 1

Views: 8564

Answers (3)

Matt Joiner
Matt Joiner

Reputation: 118500

Try this (Python 3):

new_list = list(map(str, lst))

or

new_list = [str(q) for q in lst]

Upvotes: 1

Jacob
Jacob

Reputation: 43219

newlst = [str(x) for x in lst]

You could use a list comprehension.

Upvotes: 11

Dogbert
Dogbert

Reputation: 222118

Try this:

new_list = map(str, lst)

Upvotes: 9

Related Questions