Indexing and Slicing in Python Lists Read

Indexing and Slicing in Python Lists Read

Indexing and slicing are fundamental operations to access and extract elements from a list in Python.


1. Indexing (Accessing Single Elements)

  • Lists are zero-indexed (first element is at index 0).
  • Negative indices count from the end (-1 = last element).

Example 1: Basic Indexing

python

fruits = ["apple", "banana", "cherry", "date", "fig"]

# Positive indexing
print(fruits[0])   # "apple" (1st element)
print(fruits[2])   # "cherry" (3rd element)

# Negative indexing
print(fruits[-1])  # "fig" (last element)
print(fruits[-3])  # "cherry" (3rd from the end)

Output:

text

apple
cherry
fig
cherry

2. Slicing (Extracting a Sub-List)

  • Syntax: list[start:stop:step]
    • start (inclusive), stop (exclusive), step (optional, default=1).
  • Omitting start or stop slices from the start/end.

Example 2: Basic Slicing

python

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

# Get elements from index 2 to 5 (exclusive)
print(numbers[2:5])   # [2, 3, 4]

# From start to index 4
print(numbers[:4])    # [0, 1, 2, 3]

# From index 6 to end
print(numbers[6:])    # [6, 7, 8, 9]

# Every 2nd element
print(numbers[::2])   # [0, 2, 4, 6, 8]

# Reverse the list
print(numbers[::-1])  # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Output:

text

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

Similar Posts

  • Generalization vs. Specialization

    Object-Oriented Programming: Generalization vs. Specialization Introduction Inheritance in OOP serves two primary purposes: Let’s explore these concepts with clear examples. 1. Specialization (Extending Functionality) Specialization involves creating a new class that inherits all features from a parent class and then adds new, specific features. The core idea is reusability—you build upon what already exists. Key Principle: Child Class =…

  • binary files

    # Read the original image and write to a new file original_file = open(‘image.jpg’, ‘rb’) # ‘rb’ = read binary copy_file = open(‘image_copy.jpg’, ‘wb’) # ‘wb’ = write binary # Read and write in chunks to handle large files while True: chunk = original_file.read(4096) # Read 4KB at a time if not chunk: break copy_file.write(chunk)…

  • Bank Account Class with Minimum Balance

    Challenge Summary: Bank Account Class with Minimum Balance Objective: Create a BankAccount class that automatically assigns account numbers and enforces a minimum balance rule. 1. Custom Exception Class python class MinimumBalanceError(Exception): “””Custom exception for minimum balance violation””” pass 2. BankAccount Class Requirements Properties: Methods: __init__(self, name, initial_balance) deposit(self, amount) withdraw(self, amount) show_details(self) 3. Key Rules: 4. Testing…

  • Escape Sequences in Python

    Escape Sequences in Python Regular Expressions – Detailed Explanation Escape sequences are used to match literal characters that would otherwise be interpreted as special regex metacharacters. 1. \\ – Backslash Description: Matches a literal backslash character Example 1: Matching file paths with backslashes python import re text = “C:\\Windows\\System32 D:\\Program Files\\” result = re.findall(r'[A-Z]:\\\w+’, text) print(result) #…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

Leave a Reply

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