Is there a difference between the cuts of Python lists [-1:] and [-1]?

I read a piece of code like this:

s = self.buffer_file.readline()
if s[-1:] == "\n":
    return s

And if I do this:

s = 'abc'
In [78]: id(s[-1:]), id(s[-1])
Out[78]: (140419827715248, 140419827715248)

In [79]: id(s[-1:]) is id(s[-1])
Out[79]: False

In [80]: id(s[-1:]) == id(s[-1])
Out[80]: True

It makes no sense to me, the identification numbers are the same, but the identifiers are different. For some reason they are different.

+4
source share
3 answers

The difference is that the result of slicing the list is a list

x = [1, 2, 3]

print(x[-1])  # --> 3
print(x[-1:]) # --> [3]

The second case is simply a list of one item, but it is still a list.

Note, however, that Python does not have a type charother than type str, and this means that both access and slicing elements on objects strreturn a different object str:

print("abcd"[-1])  # --> "d"
print("abcd"[-1:]) # --> "d"

, , s[-1:] s[:1] s[-1] s[0] , (- , )... :

if len(s) > 0 and s[0] == '*': ...
if s[:1] == '*': ...
+8

s[-1:], s[-1] , , .

>>> 'hi'[-1:]
'i'
>>> 'hi'[-1]
'i'
>>> ''[-1:]
''
>>> ''[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

if s[-1:] == "\n": s, if s:, False , try..except.

+7

id(s[-1:]) is id(s[-1]) , ( ) . CPython 2.

.

. http://davejingtian.org/2014/12/11/python-internals-integer-object-pool-pyintobject/.

:

Python 2.7.10 (default, Sep 23 2015, 04:34:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin

>>> s = 'abc'
>>> s[-1:]
'c'
>>> s[-1]
'c'
>>> s[-1:]
'c'
>>> a = s[-1:]
>>> b = s[-1]
>>> id(a)
4531751912
>>> id(b)
4531751912
>>> a is b
True
>>> id(a) is id(b)
False

Objects aand bare one and the same object, but they idare two intsthat are not "reference".

More about integers:

>>> 5 is 100
False
>>> 5 is 5
True
>>> 10000 is 10000
True
>>> 1000000000 is 1000000000
True
>>> a = 10000000
>>> a is 10000000
False
>>> a, b = 100000000, 100000000
>>> a is b
True
>>> a is 100000000
False
>>> id(100000000)
140715808080880
>>> id(a)
140715808080664
>>> id(b)
140715808080664
>>> id(100000000)
140715808080640
>>>

Further reading: PyPy implementation details: http://doc.pypy.org/en/latest/cpython_differences.html#object-identity-of-primitive-values-is-and-id

+5
source

Source: https://habr.com/ru/post/1616839/


All Articles