Oscalation
Oscalation

Reputation: 380

how to change the data type of the second element in a nested list

nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]

I want to convert the second element in each nested list to the int type. I am trying something like this

nested_list2 = []
[int(x[1]) for x in nested_list]

this does convert the second element to int, but i lose the rest of the data.

I've also tried this, but it colapses my nested list structure:

 [nested_list2.extend((x[0], int(x[1]))) for x in testlist]

Is it possible here to end up with something like the following

 nested_list2 = [['bob', 444], ['steve', 111], ['mark', 888]]

Upvotes: 2

Views: 1089

Answers (3)

starLord073
starLord073

Reputation: 26

nested_list2=[]
temp=[]
for i in nested_list:
    for j in i:
        temp.append(j)
    nested_list2.append(temp)
    temp=[]
for i in nested_list2:
    i[1]=int(i[1])

Try this and let me know if it is what you needed. Cheers!

Upvotes: 0

nandu kk
nandu kk

Reputation: 368

nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]
for x in nested_list:
    x[1]=int(x[1])

Upvotes: 3

jpp
jpp

Reputation: 164643

A list comprehension should be used to create a new list, not modify an existing list in place:

nested_list = [['bob', '444'], ['steve', '111'], ['mark', '888']]

res = [[name, int(num)] for name, num in nested_list]

# [['bob', 444], ['steve', 111], ['mark', 888]]

Upvotes: 4

Related Questions