Python Convert List of Integers to a List of Strings (original) (raw)
Last Updated : 09 Apr, 2025
We are given a list of integers and our task is to convert each integer into its string representation. For example, if we have a list like [1, 2, 3] then the output should be [‘1’, ‘2’, ‘3’]. In Python, there are multiple ways to do this efficiently, some of them are: using functions like map(), reduce() or even list comprehensions. Let’s explore these methods to better understand this.
Using map()
map() function applies a given function (in this case, str) to every item in the list and returns a map object, which we convert to a list.
Python `
a = [1, 2, 3, 4, 5]
Convert each element to string using map
b = list(map(str, a))
print(b)
`
Output
['1', '2', '3', '4', '5']
**Explanation:
- **map****(str, a)** applies the str function to every item in list a.
- The result is a map object, which we convert to a list using **list().
- This is one of the most efficient and readable ways to convert types in bulk.
Using List Comprehension
List comprehension is a concise way to create a new list by applying an expression to each item in an existing list. We use a list comprehension to loop through each element in the list a.
Python `
a = [1, 2, 3, 4, 5]
Convert each element using a list comprehension
b = [str(x) for x in a]
print(b)
`
Output
['1', '2', '3', '4', '5']
**Explanation:
- This loops through each element **x in the list a and applies **str(x).
- The result is collected into a new list.
Using for Loop
We can also convert the list of integers into strings by using a simple for loop. In this method, we create an empty list b. We then loop through each element x in list a, convert it to a string using str(), and append it to the list b.
Python `
a = [1, 2, 3, 4, 5]
b = [] for x in a: b.append(str(x)) # Convert each number to string and append to b
print(b)
`
Output
['1', '2', '3', '4', '5']
**Explanation:
- We start with an empty list **b.
- For each element **x in **a, we convert it using **str(x) and append it to b.
reduce() function from the functools module can also be used, although it’s a bit more complex than the previous methods. It reduces a list into a single value using a function, which can be used to build a list in this case.
Python `
from functools import reduce a = [1, 2, 3, 4, 5]
Using reduce to accumulate the list of strings
b = reduce(lambda acc, x: acc + [str(x)], a, [])
print(b)
`
Output
['1', '2', '3', '4', '5']
**Explanation:
- **reduce() applies the lambda function to accumulate a result.
- It starts with an empty list [] and adds str(x) for each element.