List Slice Step in Python

Level 388 keystrokes

This uses slice with step to extract every nth element from a list.

Python code

# Create a list of numbers 0-9
1nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# [::2] means start to end with step 2 (even indices)
2even = nums[::2]
# [1::2] means start at index 1 with step 2 (odd indices)
3odd = nums[1::2]
# Print both lists
4print(even, odd)

Output

[0, 2, 4, 6, 8] [1, 3, 5, 7, 9]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • ,× 10
  • :× 4
  • [× 3
  • ]× 3
  • =× 3
  • (× 1
  • )× 1

More Python examples at level 3

← Python typing practice