quesadyllan quesadyllan - 5 months ago 25
Python Question

list[-1:] returns last value, but is not == last value?

I'm still very new to coding, as in I've been coding for a few days. I'm trying to teach myself python by working on a small personal project. I've been playing around with list slicing, and something doesn't add up to me, which is impeding a function I'm trying to make.

By playing around in the shell (correct terminology?) I've deduced that:

>>> list1 = "hello"
>>> list2 = list(list1)
>>> list2[-1:]
>>> 'o'
>>> list2[-1:] == 'o'
>>> False
>>> list2[0]
>>> 'h'
>>> list2[0] == 'h'
>>> True

Why is this? At first I thought since maybe list2 was defined by another list, its last index would not be == to list1's because list1 could be redefined? But then I tried the first index and now I'm confused.

Lee Lee

I guess what you meant to show is

>>> list1 = 'hello'
>>> list1
>>> list2 = list(list1)
>>> list2
['h', 'e', 'l', 'l', 'o']

In this case,

>>> list2[-1]
>>> list2[-1:]

As you can see, list2[-1:] returns a list, thus it's not equal to 'o'.