Created
April 5, 2018 15:38
-
-
Save ceeblet/5c2044eb73ca4fa7ef6ce87d5793288d to your computer and use it in GitHub Desktop.
Python's list slice syntax: a few fun and useful things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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