Learn with Yasir

Share Your Feedback

List Slicing in Python: Syntax and Examples


Learn how to use Python list slicing to extract and manipulate parts of lists. This guide provides clear explanations and examples for efficient coding.

Slicing a list in Python means extracting a portion (or subsequence) of the list using a specific syntax:

Syntax:

list[start:stop:step]
  • start: index to begin slicing (inclusive)
  • stop: index to end slicing (exclusive)
  • step: how many elements to skip (default is 1)

Examples:

numbers = [10, 20, 30, 40, 50, 60, 70]

1. Get elements from index 1 to 4:

numbers[1:5]   # [20, 30, 40, 50]

2. Get every second element:

numbers[::2]   # [10, 30, 50, 70]

3. Reverse the list:

numbers[::-1]  # [70, 60, 50, 40, 30, 20, 10]

4. From index 3 to end:

numbers[3:]    # [40, 50, 60, 70]

5. From start to index 4:

numbers[:5]    # [10, 20, 30, 40, 50]

πŸ“Ί Video Tutorial: List Slicing

The video explains how to modify a list by replacing multiple elements with a single element.

This video covers:

  • βœ”οΈ A list called β€œlist1” is created with five integers [00:07].
  • βœ”οΈ The second, third, and fourth elements of the list (98, 23, and 70) are selected using slice notation [00:13].
  • βœ”οΈ These elements are replaced with the single element 20 [00:23].
  • βœ”οΈ The modified list is printed [00:29].

Tasks

  1. Positive Index Slicing
    • Given numbers = [10, 20, 30, 40, 50, 60], extract:
      • First 3 elements
      • Elements from index 2 to 4
      • Last 2 elements (using positive indices)
  2. Negative Index Practice
    • For letters = ['a', 'b', 'c', 'd', 'e', 'f']:
      • Get all elements except the last one using negative indexing
      • Extract [β€˜c’, β€˜d’] using negative indices
      • Get the last element using negative index
  3. Step Value Exercises
    • Using data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
      • Extract all even-indexed items (0, 2, 4…)
      • Get every 3rd item starting from index 1
      • Reverse the list using step value

🧠 Practice & Progress

Explore More Topics

πŸ“˜ Learn Python

Tutorials, Roadmaps, Bootcamps & Visualization Projects

Python Fundamentals

Flow Control Statements


Python Functions


Fundamentals more ...




🧠 Python Advanced

Object-Oriented Programming in Python (OOP)

More...

🧠 Modules