0

I am stuck on a problem due to a small portion of my code. I can't find why that portion of code is not working properly.

By debugging each portion of my code, I found which lines are causing unexpected results. I have written that lines below. I have defined the list here so that I do not have to copy my full code.

list1=["-7","-7","-6"]

for test in list1:

    test=int(test)

print( type( list1[0] ) )

I expected type to be int but output is coming as str instead.

balkon16
  • 1,338
  • 4
  • 20
  • 40
Udit Garg
  • 47
  • 6

3 Answers3

3

You need to modify the content of the list:

list1=["-7","-7","-6"]

for i in range(len(list1)):
    list1[i] = int(list1[i])

print(type(list1[0]))

A more pythonic approach would be to use a comprehension to change it all at once:

list1 = [int(x) for x in list1]
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

Try this to convert each item of a list to integer format :

list1=["-7","-7","-6"]
list1 = list(map(int, list1))

list1 becomes [-7, -7, -6].

Now type(list1[0]) would be <class 'int'>

Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

You forgot about appending the transformed value:

list1 = ["-7","-7","-6"]
list2 = [] # store integers
for test in list1:
    test = int(test)
    list2.append(test) # store transformed values

print(type(list2[0]))
balkon16
  • 1,338
  • 4
  • 20
  • 40