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
EasyCreate 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 belowThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2