175

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
  • 6
    Where do I get python 4.7? Me wants! In 2.7, The Tutorial covers your question quite nicely. Commented Oct 25, 2010 at 6:44

3 Answers 3

253

: 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.

8
  • 21
    Remember that [1:5] starts with the object at index 1, and the object at index 5 is not included. You can also make a soft copy of a list with [:] Commented Oct 25, 2010 at 7:51
  • 7
    Because it's not actually that easy to Google punctuation like ':', I particularly appreciated finding your answer and found it helpful. Even using something like symbolhound, its so commonly used that I was afraid I wouldn't be able to find an answer quickly.
    – Edub Kendo
    Commented Aug 3, 2013 at 11:25
  • 3
    Does not work with dictionaries. applying d[:5] is the eqivalent of d.__getitem__(slice(0, 5, None)). A slice is not hashable. Commented Jul 4, 2015 at 2:31
  • 11
    Also you can have step in there: [start:end:step], which is why [::-1] reverses with normal start and end, but backwards step.
    – Joe
    Commented Apr 28, 2016 at 19:48
  • 1
    @TomCharlesZhang these are operators operating on an iterable. If you just [1:5] Python doesn't understand what you're operating on. It has to be something like "Hello World"[1:5] for example, or ['a','b','c','d', 'e','f','g'][1:5]
    – soulseekah
    Commented Mar 3, 2021 at 12:07
22

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

0
16

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).

2
  • 7
    Why wold you want to get a subarray starting at the length of the array (a[len(a):])? Shouldn't this just return an empty subarray always since there are no elements after index len(a) - 1?
    – Ozymandias
    Commented Jun 13, 2020 at 1:10
  • 2
    @AjaxLeung empty slices are useful because you can assign to them: a = list(range(0,10)) print('a\t', a) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print('slice\t', a[3:3]) # [] a[3:3] = [10,10,10] print('new a\t', a) # [0, 1, 2, 10, 10, 10, 3, 4, 5, 6, 7, 8, 9]
    – Tim Smith
    Commented Jan 30, 2021 at 2:46

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.