Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coverting all the list elements to string using Python?

I have a list:

roll = [1, 2, 3]

For converting each of the element into a string, can we directly do roll = str(roll) rather that iterating over it and calling str() on each element? Is this a correct way?

I am new to Python, any hint in the right direction will do!

like image 588
Aadil Hoda Avatar asked Sep 01 '26 03:09

Aadil Hoda


1 Answers

That wouldn't work, since that would convert the entire list into one string:

roll = [1, 2, 3]
roll = str(roll)
print(roll)
# Prints [1, 2, 3]
print(type(roll))
# Prints <class 'str'>

You can instead use a list comprehension, to convert each item in the list one by one:

roll = [1, 2, 3]
roll = [str(r) for r in roll]
print(roll)
# Prints ['1', '2', '3']
print(type(roll))
# Prints <class 'list'>
like image 78
costaparas Avatar answered Sep 02 '26 16:09

costaparas