What You Will Learn
Beginner
- How to create and access lists
- Indexing and slicing
- Modifying list elements
Terminalpython
# Creating lists
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
empty = []
# Indexing (0-based)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last)
print(fruits[1]) # banana
# Slicing [start:end:step]
print(numbers[0:3]) # [1, 2, 3]
print(numbers[:3]) # [1, 2, 3] (from start)
print(numbers[2:]) # [3, 4, 5] (to end)
print(numbers[::-1]) # [5, 4, 3, 2, 1] (reverse!)
print(numbers[::2]) # [1, 3, 5] (every other)Modifying Lists
Terminalpython
fruits = ["apple", "banana", "cherry"]
# Change an element
fruits[0] = "avocado"
print(fruits) # ['avocado', 'banana', 'cherry']
# Add elements
fruits.append("date") # Add to end
fruits.insert(0, "apple") # Insert at index
print(fruits) # ['apple', 'avocado', 'banana', 'cherry', 'date']
# Remove elements
fruits.remove("avocado") # Remove by value
popped = fruits.pop() # Remove and return last
print(fruits) # ['apple', 'banana', 'cherry']
print(popped) # dateChecking Membership
Terminalpython
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" in fruits) # False
print("grape" not in fruits) # TruePractical Exercise
Create a list of 5 numbers
Print the first and last element
Slice: print middle 3 elements
Reverse the list: numbers[::-1]
Add and remove elements
Key Takeaways
- Lists are ordered, mutable (changeable) collections.
- Indexing: [0] is first, [-1] is last.
- Slicing: [start:end:step]. [::-1] reverses.
- append() adds to end. insert() adds at index.
- remove() by value. pop() removes and returns.
- in checks membership.
Comments
Comments
Post a Comment