Menu
Coddy logo textTech

List Slicing Part 1

Part of the Fundamentals section of Coddy's Python journey — lesson 64 of 77.

Slicing allows us to extract portions of a list using the following syntax: lst[start:stop]. For example consider this list:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Getting a portion of the list:

print(numbers[2:6])
# Output: [2, 3, 4, 5]

This gets elements from index 2 (inclusive) to index 6 (exclusive)

Omitting start parameter:

print(numbers[:5])
# Output: [0, 1, 2, 3, 4]

When start is omitted, slice begins from index 0

Omitting stop parameter:

print(numbers[5:])
# Output: [5, 6, 7, 8, 9]

When stop is omitted, slice goes until the end

challenge icon

Challenge

Easy

Create a program that receives a list as input (given) and prints the following sliced list (depends on the list length):

  • For odd-length lists: take the middle item and one item on each side (3 items total)
  • For even-length lists: take the two middle items

When dividing numbers:

  • / gives you a decimal number (5/2 = 2.5)
  • // removes the decimal part (5//2 = 2)

For this challenge, use // because list slicing only works with whole numbers.

Cheat sheet

Slicing in Python allows extracting portions of a list:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing
print(numbers[2:6])  # [2, 3, 4, 5]

# Omitting start (begins from index 0)
print(numbers[:5])   # [0, 1, 2, 3, 4]

# Omitting stop (goes until the end)
print(numbers[5:])   # [5, 6, 7, 8, 9]

Syntax: lst[start:stop] (start is inclusive, stop is exclusive)

Try it yourself

lst = input().split(",")
# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals