List Slicing Programs
Demonstrate common list slicing operations (first N, last N, every Kth element).
BeginnerTopic: List Programs
Python List Slicing Programs Program
This program helps you to learn the fundamental structure and syntax of Python programming.
# Program to demonstrate list slicing
items = input("Enter list elements separated by space: ").split()
N = int(input("Enter N for first/last N elements: "))
K = int(input("Enter K for every Kth element: "))
print("First N elements:", items[:N])
print("Last N elements:", items[-N:])
print("Every Kth element:", items[::K] if K != 0 else "K cannot be 0")Output
Enter list elements separated by space: a b c d e f Enter N for first/last N elements: 2 Enter K for every Kth element: 2 First N elements: ['a', 'b'] Last N elements: ['e', 'f'] Every Kth element: ['a', 'c', 'e']
Understanding List Slicing Programs
We showcase basic slicing patterns: prefix, suffix, and step-based selection.
Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.