-1

Program 1:

lines = [['5.1', '3.5', '1.4', '0.2', 0],
    ['5.2', '2.5', '1.3', '0.1', 1]]
for line in lines:
    line = [float(i) for i in line]
    print(line)
print(lines)

Program 2

lines = [['5.1', '3.5', '1.4', '0.2', 0],
    ['5.2', '2.5', '1.3', '0.1', 1]]
for line in lines:
    for i in range(len(line)):
        line[i] = float(line[i])
    print(line)

print(lines)

Couldn't understand why each line had been modified but lines had not, can anyone explain why?

John
  • 331
  • 2
  • 11

1 Answers1

2

In the Program 1, you are reassigning new value to line element. Hence it is not referring the same lines element, it has a new address after assignment is done using assignment operator(=).

Output:

[5.1, 3.5, 1.4, 0.2, 0.0]
[5.2, 2.5, 1.3, 0.1, 1.0]
[['5.1', '3.5', '1.4', '0.2', 0], ['5.2', '2.5', '1.3', '0.1', 1]]

Observe that you have passed lines elements as string and you are getting lines as it is. But line elements as float(which is not reflected in lines).

In the Program 2, you are accessing the element of line which is the element of lines. It is holding address of lines element.

Output:

[5.1, 3.5, 1.4, 0.2, 0.0]
[5.2, 2.5, 1.3, 0.1, 1.0]
[[5.1, 3.5, 1.4, 0.2, 0.0], [5.2, 2.5, 1.3, 0.1, 1.0]]

Observe that you have passed lines elements as string and now you are getting lines elements as float.

HimanshuGahlot
  • 561
  • 4
  • 11
  • Is it an unique behavior for python? Never noticed this in other programming languages – John Sep 03 '18 at 05:45
  • Hi buddy, welcome to stackoverflow, To be very true, I am not that much aware of any other language, but it happens in python. By the way if this answer satisfied your craving for knowledge kindly upvote my answer its keep me motivated. – HimanshuGahlot Sep 03 '18 at 07:34