Python How to Convert List of Integers to Strings
You can convert a list of integers to strings in Python by using a list comprehension like
[str(i) for i in int_list] which creates a new list with each integer converted to a string.Examples
Input[1, 2, 3]
Output['1', '2', '3']
Input[10, 0, -5]
Output['10', '0', '-5']
Input[]
Output[]
How to Think About It
To convert each integer in a list to a string, think of going through the list one by one and changing each number into its text form. This is like writing down numbers as words on paper. Using a list comprehension helps do this quickly and clearly.
Algorithm
1
Get the input list of integers.2
Create a new empty list to hold strings.3
For each integer in the input list, convert it to a string.4
Add the string to the new list.5
Return the new list of strings.Code
python
int_list = [1, 2, 3, 4] str_list = [str(i) for i in int_list] print(str_list)
Output
['1', '2', '3', '4']
Dry Run
Let's trace the list [1, 2, 3] through the code
1
Start with input list
int_list = [1, 2, 3]
2
Convert each integer to string
str_list = ['1', '2', '3']
3
Print the result
Output: ['1', '2', '3']
| Integer | String |
|---|---|
| 1 | '1' |
| 2 | '2' |
| 3 | '3' |
Why This Works
Step 1: List comprehension
The list comprehension [str(i) for i in int_list] loops over each integer i in the list.
Step 2: Convert integer to string
Each integer i is converted to a string using the str() function.
Step 3: Create new list
All converted strings are collected into a new list which is returned.
Alternative Approaches
Using map() function
python
int_list = [1, 2, 3] str_list = list(map(str, int_list)) print(str_list)
This uses the built-in <code>map</code> to apply <code>str</code> to each item, which is concise and readable.
Using a for loop
python
int_list = [1, 2, 3] str_list = [] for i in int_list: str_list.append(str(i)) print(str_list)
This is more verbose but clear for beginners to understand the step-by-step process.
Complexity: O(n) time, O(n) space
Time Complexity
The code loops through each of the n integers once, converting each to a string, so time is O(n).
Space Complexity
A new list of strings is created with the same length as the input, so space is O(n).
Which Approach is Fastest?
List comprehension and map() have similar performance; for loops are slightly slower but clearer for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| List comprehension | O(n) | O(n) | Concise and readable code |
| map() function | O(n) | O(n) | Functional style, concise |
| For loop | O(n) | O(n) | Step-by-step clarity for beginners |
Use list comprehension for a clean and fast way to convert all integers to strings in one line.
Trying to convert the whole list directly with
str(int_list) which returns a single string, not a list of strings.