slice list python code example

Example 1: python slice an array

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array
Example:
>>> a = [1, 2, 3, 4, 5, 6, 7, 8]
>>> a[1:4]
[2, 3, 4]

Example 2: python how to slice lists

# Basic syntax:
your_list[start:stop:step]

# Note, Python is 0-indexed
# Note, start is inclusive but stop is exclusive
# Note, if you leave start blank, it defaults to 0. If you leave stop
# 	blank, it defaults to the length of the list. If you leave step
# 	blank, it defaults to 1.
# Note, a negative start/stop refers to the index starting from the end
# 	of the list. Negative step returns list elements from right to left 

# Example usage:
your_list = [0, 1, 2, 3, 4, 5]
your_list[0:5:1]
--> [0, 1, 2, 3, 4] # This illustrates how stop is not inclusive

# Example usage 2:
your_list = [0, 1, 2, 3, 4, 5]
your_list[::2] # Return list items for even indices
--> [0, 2, 4]

# Example usage 3:
your_list = [0, 1, 2, 3, 4, 5]
your_list[1::2] # Return list items for odd indices
--> [1, 3, 5]

# Example usage 4:
your_list = [0, 1, 2, 3, 4, 5]
your_list[4:-6:-1] # Return list items from 4th element from the left to 
#	the 6th element from the right going from right to left
--> [4, 3, 2, 1]
# Note, from the right, lists are 1-indexed, not 0-indexed

Example 3: slicing in python list

a = [1,2,3,4,5]
a[m:n] # elements grrater than equal to m and less than n
a[1:3] = [2,3]

Example 4: slicing in python

word = "Example"

# Obtain the first 3 characters of "Example"
# E x a m p l e
# 0 1 2 3 4 5 6
# First 3 characters = "Exa"
sliced_word = word[:3] # Gives you "Exa"

# Everything after character #3 = "mple"
second_sliced_word = word[3:] # Gives you "mple"

Example 5: python list slice sybtax

# [start:stop:step]
# for example ...
l = [1, 2, 3, 4, 5]
l[1:4] # elements from 1 (inclusive) to 4 (exclusive)
l[2:5:2] # elements from 2 (inclusive) to 5 (exclusive) going up by 2

Example 6: python array slice

>>> a[1:4]
[2, 3, 4]