Colon (:) in Python list index

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

: 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 and strings, too.

Solution 2 - Python

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

Solution 3 - Python

a[len(a):] - This gets you the length of a to the end. It selects a range. If you reverse a[:len(a)] it will get you the beginning to whatever is len(a).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkuriouscoderView Question on Stackoverflow
Solution 1 - PythonsoulseekahView Answer on Stackoverflow
Solution 2 - PythonjoniView Answer on Stackoverflow
Solution 3 - PythonGISmanView Answer on Stackoverflow