Negative slicing in Python lists

Negative slicing in Python lists lets you access elements from the end of the list. It’s a handy way to get a portion of a list without knowing its exact length. In negative slicing, you use negative numbers as indices. The index -1 refers to the last element, -2 to the second to last, and so on. The basic syntax is list[start:stop:step], where start and stop can be negative.

Here are 20 examples of negative slicing with a simple list numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

Basic Negative Slicing

  1. Get the last element: numbers[-1]Result: 9
  2. Get the last three elements: numbers[-3:]Result: [7, 8, 9]
  3. Get all elements except the last one: numbers[:-1]Result: [0, 1, 2, 3, 4, 5, 6, 7, 8]
  4. Get elements from the third to last to the second to last: numbers[-3:-1]Result: [7, 8]
  5. Get elements from the fifth to last to the last: numbers[-5:]Result: [5, 6, 7, 8, 9]

Combining Positive and Negative Indices

  1. Get elements from index 2 to the second to last: numbers[2:-1]Result: [2, 3, 4, 5, 6, 7, 8]
  2. Get elements from the third to last to index 8: numbers[-3:9]Result: [7, 8]
  3. Get elements from index 0 to the fourth to last: numbers[:-4]Result: [0, 1, 2, 3, 4, 5]
  4. Get elements from the sixth to last to index 7: numbers[-6:8]Result: [4, 5, 6, 7]

Using Negative Step Values

  1. Reverse the entire list: numbers[::-1]Result: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  2. Get the last three elements in reverse order: numbers[-1:-4:-1]Result: [9, 8, 7]
  3. Reverse the list from the second to last to the third element: numbers[-2:2:-1]Result: [8, 7, 6, 5, 4, 3]
  4. Get elements from the end, skipping every other one: numbers[::-2]Result: [9, 7, 5, 3, 1]
  5. Get the first three elements in reverse order using a negative step: numbers[2::-1]Result: [2, 1, 0]
  6. Reverse the first five elements: numbers[4::-1]Result: [4, 3, 2, 1, 0]

More Complex Examples

  1. Get elements from the fourth to last to the end, with a step of 2: numbers[-4::2]Result: [6, 8]
  2. Slice from the last element to the fifth element in reverse: numbers[-1:4:-1]Result: [9, 8, 7, 6, 5]
  3. Get the middle part of the list, from the fourth to last to the third element: numbers[-4:3]Result: [] (An empty list, since the start index is after the stop index and the step is positive)
  4. Get every other element in reverse order, starting from the second to last: numbers[-2::-2]Result: [8, 6, 4, 2, 0]
  5. Get the first three elements by slicing from the fourth to last element in reverse: numbers[-8:-11:-1]Result: [2, 1, 0]

Similar Posts

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • Python Program to Check Pangram Phrases

    Python Program to Check Pangram Phrases What is a Pangram? A pangram is a sentence or phrase that contains every letter of the alphabet at least once. Method 1: Using Set Operations python def is_pangram_set(phrase): “”” Check if a phrase is a pangram using set operations “”” # Convert to lowercase and remove non-alphabetic characters…

  • re.sub()

    Python re.sub() Method Explained The re.sub() method is used for searching and replacing text patterns in strings. It’s one of the most powerful regex methods for text processing. Syntax python re.sub(pattern, repl, string, count=0, flags=0) Example 1: Basic Text Replacement python import re text = “The color of the sky is blue. My favorite color is blue too.” #…

  • Curly Braces {} ,Pipe (|) Metacharacters

    Curly Braces {} in Python Regex Curly braces {} are used to specify exact quantity of the preceding character or group. They define how many times something should appear. Basic Syntax: Example 1: Exact Number of Digits python import re text = “Zip codes: 12345, 9876, 123, 123456, 90210″ # Match exactly 5 digits pattern = r”\d{5}” # Exactly…

Leave a Reply

Your email address will not be published. Required fields are marked *