📋

How to Work with Lists in Python

PythonBeginner

Create, modify, and iterate through lists.

Code Example

Python
# Lists in Python
fruits = ["apple", "banana", "cherry", "date"]

# Access elements
print(f"First fruit: {fruits[0]}")
print(f"Last fruit: {fruits[-1]}")

# Add items
fruits.append("elderberry")
print(f"\nAfter append: {fruits}")

# List comprehension
squares = [x**2 for x in range(1, 6)]
print(f"\nSquares: {squares}")

# Filtering
evens = [x for x in range(1, 11) if x % 2 == 0]
print(f"Evens: {evens}")

Explanation

Lists are ordered, mutable collections. Use indexing, append(), and list comprehensions for powerful operations.

Related Tutorials