Colon (:) in Python list index


Question

I'm new to Python. I see : used in list indices especially when it's associated with function calls.

Python 2.7 documentation suggests that lists.append translates to a[len(a):] = [x]. Why does one need to suffix len(a) with a colon?

I understand that : is used to identify keys in dictionary.

1
92
6/22/2016 6:52:08 PM

Accepted Answer

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples, dictionaries and lists, too.

141
3/12/2018 7:42:45 PM

slicing operator. http://docs.python.org/tutorial/introduction.html#strings and scroll down a bit


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon