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

  • Special Character Classes Explained with Examples

    Special Character Classes Explained with Examples 1. [\\\^\-\]] – Escaped special characters in brackets Description: Matches literal backslash, caret, hyphen, or closing bracket characters inside character classes Example 1: Matching literal special characters python import re text = “Special chars: \\ ^ – ] [” result = re.findall(r'[\\\^\-\]]’, text) print(result) # [‘\\’, ‘^’, ‘-‘, ‘]’] # Matches…

  • Positional-Only Arguments in Python

    Positional-Only Arguments in Python Positional-only arguments are function parameters that must be passed by position (order) and cannot be passed by keyword name. Syntax Use the / symbol in the function definition to indicate that all parameters before it are positional-only: python def function_name(param1, param2, /, param3, param4): # function body Simple Examples Example 1: Basic Positional-Only Arguments python def calculate_area(length,…

  • 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…

  • Currency Converter

    Challenge: Currency Converter Class with Accessors & Mutators Objective: Create a CurrencyConverter class that converts an amount from a foreign currency to your local currency, using accessor and mutator methods. 1. Class Properties (Instance Variables) 2. Class Methods 3. Task Instructions

  • Python Input Function: A Beginner’s Guide with Examples

    The input() function in Python is used to take user input from the keyboard. It allows your program to interact with the user by prompting them to enter data, which can then be used in your code. By default, the input() function returns the user’s input as a string. Syntax of input() python Copy input(prompt) Key Points About input() Basic Examples of input() Example…

  • Formatted printing

    C-Style String Formatting in Python Python supports C-style string formatting using the % operator, which provides similar functionality to C’s printf() function. This method is sometimes called “old-style” string formatting but remains useful in many scenarios. Basic Syntax python “format string” % (values) Control Characters (Format Specifiers) Format Specifier Description Example Output %s String “%s” % “hello” hello %d…

Leave a Reply

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