Search this site
Embedded Files
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
AIMD GPDS Courses
  • Home
  • Courses
  • Contact
  • More
    • Home
    • Courses
    • Contact

日本語  ❯

Lesson 1    ❮    Lesson List    ❮    Top Page

1.1 Variables

1.2 Strings

1.3 Numbers

1.4 Lists

1.5 List Methods

❯  1.6  Slice Operator  

⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
EXPECTED COMPLETION TIME
❲▹❳  Video   9m 8s
☷  Interactive readings   5m

Using Colon (:) in List for slicing

To get a part (slice) of a list you can use the colon operator [start : end]. 

Note that the end index is NOT included in the list (exclusive) while the start index is included (inclusive). You can also use a negative index.

The following diagram helps to see how the slice works:

 +---+---+---+---+---+---+

 | P | y | t | h | o | n |

 +---+---+---+---+---+---+

 0   1   2   3   4   5   6

-6  -5  -4  -3  -2  -1 

Omitting Index in Slice Operator

If you omit the first index in a slice (like foods[:3]), it will automatically start at the beginning of the list. 

Similarly, you can omit the second index (like foods[2:]), if you want the rest of the list to be included.

Slicing a List with Steps

The syntax of a Slice operator using double colon is [start : stop : steps]. 

start indicates the number from where the slicing will start,

stop indicates the number where the slicing will stop, and

steps indicates the number of jumps interpreter will take to slice the list.

Copying a List

To copy a list, you can use a slice of the original list with both indexes omitted (like this foods[:]).  You can also use list.copy()

This is basically a copy of the original list.

WRITE BETTER CODE
Whitespaces inside Slices

In a slice, the colon acts as a binary operator, and should have equal amounts on either side (treating it as the operator with the lowest priority). 

In an extended slice, both colons must have the same amount of spacing applied. Exception: when a slice parameter is omitted, the space is omitted.

©2023. All rights reserved.  Samy Baladram,
Graduate Program in Data Science - GSIS - Tohoku University
Google Sites
Report abuse
Page details
Page updated
Google Sites
Report abuse