Skip to content

Instantly share code, notes, and snippets.

@ncalm
Created May 2, 2023 23:39
Show Gist options
  • Select an option

  • Save ncalm/c93a024b4b5458bd973e646339a7cf05 to your computer and use it in GitHub Desktop.

Select an option

Save ncalm/c93a024b4b5458bd973e646339a7cf05 to your computer and use it in GitHub Desktop.
Random examples of list slicing in Python
# Lists are zero-indexed
# We can provide three-part slices as list[start:stop:step]
# If start is omitted, start at the first item
# If stop is omitted, stop at the last item
# If step is omitted, step by 1
fruits = ['Apple','Orange',
'Pear','Pineapple',
'Grape','Berry']
# fruits[start:stop:step]
def labelprint(label,expr):
print(f"{label}:\n {expr}\n")
labelprint("1st to 3rd",fruits[:3])
# 1st to 3rd:
# ['Apple', 'Orange', 'Pear']
labelprint("2nd to end",fruits[1:])
# 2nd to end:
# ['Orange', 'Pear', 'Pineapple', 'Grape', 'Berry']
labelprint("reversed",fruits[::-1])
# reversed:
# ['Berry', 'Grape', 'Pineapple', 'Pear', 'Orange', 'Apple']
labelprint("Even-indexed",fruits[::2])
# Even-indexed:
# ['Apple', 'Pear', 'Grape']
labelprint("Odd-indexed",fruits[1::2])
# Odd-indexed:
# ['Orange', 'Pineapple', 'Berry']
labelprint("Eclude last 2",fruits[:-2])
# Eclude last 2:
# ['Apple', 'Orange', 'Pear', 'Pineapple']
labelprint("Last 2",fruits[-2:])
# Last 2:
# ['Grape', 'Berry']
labelprint("Middle 2 - v1",fruits[2:4])
# Middle 2 - v1:
# ['Pear', 'Pineapple']
labelprint("Middle 2 - v2",fruits[2:-2])
# Middle 2 - v2:
# ['Pear', 'Pineapple']
labelprint("Every 3rd item starting from the 2nd",fruits[1::3])
# Every 3rd item starting from the 2nd:
# ['Orange', 'Grape']
labelprint("Every 3rd item starting from the end, backwards",fruits[-1::-3])
# Every 3rd item starting from the end, backwards:
# ['Berry', 'Pear']
labelprint("First 4 in reverse order",fruits[3::-1])
# First 4 in reverse order:
# ['Pineapple', 'Pear', 'Orange', 'Apple']
labelprint("First 3 even-indexed",fruits[::2][:3])
# First 3 even-indexed:
# ['Apple', 'Pear', 'Grape']
labelprint("Every 3rd starting from 2nd, up to but not including last",fruits[1:-1:3])
# Every 3rd starting from 2nd, up to but not including last:
# ['Orange', 'Grape']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment