Answers for "python how does slicing work"

19

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
Posted by: Guest on October-03-2020
10

python slice

# array[start:stop:step]

# start = include everything STARTING AT this idx (inclusive)
# stop = include everything BEFORE this idx (exclusive)
# step = (can be ommitted) difference between each idx in the sequence

arr = ['a', 'b', 'c', 'd', 'e']

arr[2:] => ['c', 'd', 'e']

arr[:4] => ['a', 'b', 'c', 'd']

arr[2:4] => ['c', 'd']

arr[0:5:2] => ['a', 'c', 'e']

arr[:] => makes copy of arr
Posted by: Guest on June-09-2020
0

is : and :: the same in python slice

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed
Posted by: Guest on October-11-2020

Code answers related to "python how does slicing work"

Python Answers by Framework

Browse Popular Code Answers by Language