Python - Slice Notation

Card Puncher Data Processing

About

Slicing (sub-list) returns a list of elements in a sequence from the position a to the position before b.

Syntax

sequence[a:b:c]

where in the sequence[a:b:c]:

  • a is the first element of the slice. It can be negative (ie -2 means start from the last two elements of list)
  • b is the last element of the slice (not include)
  • c is the number of element to skip

Example

without skipping

my_list = [0, 1, 2, 3]
first_three_items = my_list[0:3]  # The first three items
first_three_items = my_list[:3]  # of 
last_two_items = my_list[len(my_list)-2:]  # will return the last two items

print my_list
# Prints [0, 1, 2, 3]

print first_three_items
# Prints [0, 1, 2]

print last_two_items
# Prints [2,3]

With skipping

>>> my_list = [0, 1, 2, 3]
>>> my_list[::2]
[0, 2]
>>> my_list[1::2]
[1, 3]





Discover More
Card Puncher Data Processing
Python - List

Lists are used to store a collection of different pieces of information in a sequence order of under a single variable name. A list can be used to implement a . A list is mutable whereas a tuple is not....
Card Puncher Data Processing
Python - Sequence (type)

The following data structure are sequence: Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two...
Card Puncher Data Processing
Python - String (str type)

in Python A string literal is a sequence data type. Strings in Python are: sequence with characters as elements Each character in a string has a subscript or offset (id). The number starts at...



Share this page:
Follow us:
Task Runner