Skip to content

Instantly share code, notes, and snippets.

@ceeblet
Created April 5, 2018 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ceeblet/5c2044eb73ca4fa7ef6ce87d5793288d to your computer and use it in GitHub Desktop.
Save ceeblet/5c2044eb73ca4fa7ef6ce87d5793288d to your computer and use it in GitHub Desktop.
Python's list slice syntax: a few fun and useful things
# Python's list slice syntax can be used without indices
# for a few fun and useful things:
# You can clear all elements from a list:
>>> lst = [1, 2, 3, 4, 5]
>>> del lst[:]
>>> lst
[]
# You can replace all elements of a list
# without creating a new list object:
>>> a = lst
>>> lst[:] = [7, 8, 9]
>>> lst
[7, 8, 9]
>>> a
[7, 8, 9]
>>> a is lst
True
# You can also create a (shallow) copy of a list:
>>> b = lst[:]
>>> b
[7, 8, 9]
>>> b is lst
False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment