Home > other >  Why isn't my list elements getting casted to int?
Why isn't my list elements getting casted to int?

Time:03-04

casting function

(I wrote list instead of the actual list names for better understanding)

I'm reading from a file with one number at each line. Then I made it into a list[] and I did list.append(line.replace("\n", "").strip())

When executing the function I wrote - list = inteles(list)

I tried restarting vs code, but it didn't work.

CodePudding user response:

Why not list.append(int(line.replace("\n", "").strip()))

CodePudding user response:

Since when you say for x in y, the x you get isn't able to change the value of the real x in the list. (except with modifying class attributes I believe)

To fix this, just do a list comprehension:

def inteles(lista):
  return [int(ele) for ele in lista]

CodePudding user response:

You are not changing the value of the original list, you are not creating a new list either, you are just changing the value of a local variable (to that function). If you want to get a list with all strings converted to a integer, you should create a new list in the function and append the changed local variable to that local list and then return that local list.

Below is a example of that:

foist = [1, 3, "4", "72"]

def inteles(lista):
    newlist = []
    for sor in lista:
        sor = int(sor)
        newlist.append(sor)

    return(newlist)
  • Related