Spex3
    

Python Data Structures: Lists 📋


    

    

A list in Python is an ordered, mutable (changeable) collection of elements. Lists can store integers, floats, strings, and even other lists.

1️⃣ Creating Lists

Lists are created using square brackets [].

🔹 Empty List

my_list = []
print(my_list) # Output: []

🔹 List with Elements


fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

🔹 List with list() Constructor

new_list = list((10, 20, 30)) # Tuple converted to list
print(new_list) # Output: [10, 20, 30]


2️⃣ Accessing Elements (Indexing & Slicing)
🔹 Indexing (Access by Position)
Python uses zero-based indexing.


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

print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: cherry (last item)

🔹 Slicing (Extracting a Subset)
list[start:end:step]

start – Starting index (default: 0).

end – Up to but not including (default: end of list).

step – Skips elements (default: 1).


numbers = [10, 20, 30, 40, 50, 60]

print(numbers[1:4]) # Output: [20, 30, 40] (from index 1 to 3)
print(numbers[:3]) # Output: [10, 20, 30] (from start to index 2)
print(numbers[::2]) # Output: [10, 30, 50] (every second element)
print(numbers[::-1]) # Output: [60, 50, 40, 30, 20, 10] (reverse list)

3️⃣ List Methods (Modifying Lists)

Method Description
append(item) Adds item at the end
insert(index, item) Inserts item at index
extend(iterable) Adds multiple items
remove(item) Removes first occurrence
pop(index) Removes item at index (default: last)
clear() Removes all elements
index(item) Returns first index of item
count(item) Counts occurrences of item
sort() Sorts in ascending order
reverse() Reverses the list
copy() Returns a copy of the list

🔹 Adding Elements

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']

fruits.extend(["grape", "mango"])
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'grape', 'mango']

🔹 Removing Elements

fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape', 'mango']

fruits.pop(2)
print(fruits) # Output: ['apple', 'orange', 'grape', 'mango']

fruits.clear()
print(fruits) # Output: []

🔹 Sorting and Reversing

numbers = [4, 2, 8, 1, 7]
numbers.sort()
print(numbers) # Output: [1, 2, 4, 7, 8]

numbers.reverse()
print(numbers) # Output: [8, 7, 4, 2, 1]

4️⃣ List Comprehension (One-Line List Creation)
List comprehensions provide a shorter way to create lists.

🔹 Example: Creating a List with a Loop


squares = [x**2 for x in range(1, 6)]
print(squares) # Output: [1, 4, 9, 16, 25]


    Date: 2025-03-22 00:00:00.000000