Is there a simple way to convert a list of type str to one of type int?

0

This is what I try:

example1:

a=['1','2','3','4']

for m in range(len(a)):
int(a[m])

print(a)

But then I realized that for example in:

example 2:

a=['1','2','3','4']

b= []


int(a[0])

b = b + [a[0]]


print(b)

#Output b = ['1']

Which means that int (a [0]) does not do anything that I could check. Could you give me advice on what I could do? I'm a little lost here.

    
asked by juan 13.11.2018 в 01:50
source

2 answers

1

I think you're under the impression of doing this:

int(a[0])

before this:

b = b + [a[0]]

It has the effect of changing the first element of the array a from string to int.

This is not the case, in fact, int(a[0]) returns you a 1 , which is the result of transforming the component 0 of the array a into%. But this operation does not change the array element in the array itself, but returns a copy of a[0] already transformed to integer type.

To achieve what you want, you must do this:

b = b + [int(a[0])]

In this way, you create a list that contains the number 1 by means of the expression [int(a[0])] and then unes the elements of the list b and the list [int(a[0])] with the expression b = b + [int(a[0])] .

    
answered by 13.11.2018 / 02:36
source
0

with the function int () combierte string a int

a=['1','2','3','4']

b= [int(x) for x in a]

print(b)
    
answered by 13.11.2018 в 02:28