Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python Peculiarity: Copying Lists Using Slice

$
0
0

Being an experienced developer but a n00b to python, I’ve decided to pick up an excellentbook named “Effective Python” by Brett Slatkin .

The book contains a heap-load of useful information about different idioms in the Python language and echo-system, and a few peculiar gems such as:

Copying Lists Using Slice

Python’s slice syntax lets us create subsets of lists by specifying different indices, for example:

A subset excluding the first element >> a_list = [1, 2, 3] >>> a_list[1:] [2, 3] A subset excluding the lastelement >> a_list = [1, 2, 3] >>> a_list[:-1] [1, 2]

Now, being developers we’re very likely to use this feature with variables:

>> n = 1

>>> a_list = [1, 2, 3] >>> a_list[-n:] [3]

But see what happens if n is replaced by zero, making our start index -0:

>> n = 0

>>> a_list = [1, 2, 3] >>> a_list[-n:] [1, 2, 3] Our list has beencopied in its entirety!

Viewing all articles
Browse latest Browse all 9596

Trending Articles