J. Does J. Does - 2 days ago 5
Python Question

different result in pycharm and python consol using slicing step

1/ for this Python3.5 code

a=[1,2,3,4,5,6,7,8]
a[::-1]
print(a)


python IDE output (the expected result):

[8, 7, 6, 5, 4, 3, 2, 1]


Pycharm output (a wrong result):

[1, 2, 3, 4, 5, 6, 7, 8]


I find it confusing to get different result depending on the console. Why is it different?

2/ Idem for this one:

x = "Hello World !"
x[6:2:-1]
print(x)


python output:

'W ol'


Pycharm output:

Hello World !

Answer

I agree with jasonharper here, what PyCharm shows you is correct, since you do not actually change a.

The only behaviour where you would get this is in an interactive python session. So if you call python in your console, run a=[1,2,3,4], enter and then a[::-1] you will get the result of that computation in the console. If you then run a again you will see that a did not change afterall.

Comments