Python List

1. Creating a List

empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [10, "Python", True, 5.5]

print(empty_list)
print(numbers)
print(mixed)

Lists are ordered, mutable collections that can store heterogeneous data.


2. Accessing List Elements (Indexing)

fruits = ["apple", "banana", "orange"]

print(fruits[0])   # First element
print(fruits[-1])  # Last element

Lists support both positive and negative indexing.


3. Slicing Lists

numbers = [0, 1, 2, 3, 4, 5]

print(numbers[1:4])   # Output: [1, 2, 3]
print(numbers[:3])    # Output: [0, 1, 2]
print(numbers[3:])    # Output: [3, 4, 5]

Extracts a sublist using slice notation.


4. Modifying List Elements

Lists are mutable and allow in-place updates.


5. Adding Elements to a List

  • append() adds at the end

  • insert() adds at a specific index


6. Removing Elements from a List

  • remove() deletes by value

  • pop() deletes by index (default last)


7. List Length and Membership

Used for validation and condition checks.


8. List Iteration

Lists are iterable and commonly used with loops.


9. List Comprehension

Concise way to generate lists using expressions.


10. Sorting and Reversing Lists

Used to reorder list elements in-place.


Last updated