How to turn a list of strings into a list of lists (containing ints)

Question:

I want to turn lst = ['123', '456', '789'] into lst = [[1,2,3], [4,5,6], [7,8,9]].

I tried:

for i in range(len(lst)):
    lst[i] = list(lst[i])

This produced lst = [['1','2','3'], ['4','5','6'], ['7','8','9']].

How can I turn those string numbers into integers?

Note: I can’t use map.

Asked By: Programming Noob

||

Answers:

Here is the solution:

lst = [['123'],['456'],['789']]
ans = []
temp = []

for i in lst:
    for j in i:
        temp = list(j)
        for k in range(len(temp)):
            temp[k] = int(temp[k])
        ans.append(temp)
        
print(ans)
# output - [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Answered By: rockzxm

Well, here is a simple solution for your problem:

final_list = []
for i in lst:
    tmp_list = []
    text = str(i[0])
    for c in text:
        tmp_list.append(int(c))
    final_list.append(tmp_list)
Answered By: youssef
lst = ['123','456','789']
for i in range(len(lst)):
    lst[i] = [int(x) for x in lst[i]]
Answered By: Byron

List comprehension approach:

lst = ['123', '456', '789']
lst = [[int(i) for i in string_number] for string_number in lst]
Answered By: Karol Milewczyk
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.