0

I'm new at Python and I have an assginment which is read a file and convert it to matrix. My file is:

n 5
0 -- 3
0 -- 4
1 -- 2
1 -- 3
2 -- 4
3 -- 3

First of all,I have to make a "5X5" matrix. I read 5 like this:

f = open("graph.txt")
    mylist = f.readlines()
    a = mylist[0][2]

When say print a it prints 5. In order to make a matrix I need to convert this string to integer. However, when I used int(a) function, it remained a str. How can I change it to integer permanently?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
jdyg
  • 711
  • 2
  • 8
  • 16

2 Answers2

3

int creates a new value but does not change the original one. So, to actually change the value, you must do something like

list[0][2] = int(list[0][2])
Fabien
  • 12,486
  • 9
  • 44
  • 62
0

use the int() constructor to assign to a:

a = int(list[0][2])

Note that this will raise an exception if the string cannot be converted to int.

Ber
  • 40,356
  • 16
  • 72
  • 88