List Slicing (last index minus 1)

Stupid bug caused because I didn’t remember this very simple fact! Suppose we have a list:

mylist = [1,2,3,4,5]

And we want to slice only the first two elements: [1,2].
Writing this:

print mylist[0:1]

will actually only give us this:

[1]

If we want to print the first two elements, we need to write

print mylist[0:2]

and then we get

[1,2]

because Python always selects the last index minus 1.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: