Changing data types in a Python list

Asked

Viewed 301 times

3

I have a list x, with 10 numbers, being all of them whole. I’d like to turn them all into numbers like float, but I can’t perform that conversion.

Code:

lista = [1,2,3,4,5,6,7,8,9,10]


for i in acs:
    acs[i]= float(i)

Besides that way, I also tried the following:

for i in acs:
    i = float(i)

What I’m doing wrong in this code?

2 answers

5


The error there is that there is no variable acs declared with an eternal object assigned to it.

A tip on how to solve with fewer lines and well readable:

Scroll through all the items in the list turning them into a float and storing the new object of the list type in the variable of your preference.

lista = [1,2,3,4,5,6,7,8,9,10]
lista_float = [float(item) for item in lista]

You can do it with a for out of a list comprehension, which is easier to understand for those who come from other languages:

lista = [1,2,3,4,5,6,7,8,9,10]
lista_float = []
for item in lista:
    lista_float.append(float(item))

The .append() I used there to add items to an already created list.

2

acs ñ esta declarado

using append

lista = [1,2,3,4,5,6,7,8,9,10]
acs = []

for i in lista:
    acs.append(float(i))

using map

lista = [1,2,3,4,5,6,7,8,9,10]
acs = [*map(float, lista)]

using understanding

lista = [1,2,3,4,5,6,7,8,9,10]
acs = [float(x) for x in lista]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.