Python:Python Lists: Operations, Slicing, and Built-in Methods
Python•Lists

Python Lists: Operations, Slicing, and Built-in Methods

Python lists allow storing heterogeneous elements, slicing, indexing from the rear with negative numbers, and appending/popping items dynamically.

Syntax

items = [element1, element2, ...] items.append(new_element) slice_sub = items[start:stop:step]

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
start:stop:stepSlice IndicesExtracts sublist from start index up to stop (exclusive).
append()MethodAdds an item to the end of the list in place.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Python List Operations and Slicing
fruits = ["Apple", "Banana", "Cherry"]

# Adding & modifying elements
fruits.append("Dragonfruit")
fruits.insert(1, "Blueberry")
print(f"Modified List: {fruits}")

# Slicing operations
numbers = [10, 20, 30, 40, 50, 60]
print(f"First 3:   {numbers[:3]}")
print(f"Last 2:    {numbers[-2:]}")
print(f"Reversed:  {numbers[::-1]}")

# List comprehension (idiomatic Python)
evens = [x for x in numbers if x % 20 == 0]
print(f"Divisible by 20: {evens}")
Expected Output:
Modified List: ['Apple', 'Blueberry', 'Banana', 'Cherry', 'Dragonfruit']
First 3:   [10, 20, 30]
Last 2:    [50, 60]
Reversed:  [60, 50, 40, 30, 20, 10]
Divisible by 20: [20, 40, 60]

How It Works: Step-by-Step

  • Lines 5-6: Demonstrates append() and insert() modifying lists in place.
  • Lines 11-13: Applies slicing syntax: [start:stop:step]. [::-1] reverses the list.
  • Line 16: Applies list comprehension for declarative filtering.

Key Concepts

  • Lists are mutable: you can change, add, and remove items after creation.
  • Negative indices count backwards from the end (-1 is the last item).
  • List comprehensions offer concise syntax for transforming and filtering lists.

Common Mistake: Assigning the result of list.append() to a variable

append() mutates the list in place and returns None. Assigning it overwrites your list with None.

❌ Incorrect
numbers = [1, 2, 3]
numbers = numbers.append(4) # numbers becomes None!
✅ Correct
numbers = [1, 2, 3]
numbers.append(4) # numbers is now [1, 2, 3, 4]

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler