Python List Exp
Python List Exp
Creating a List
# Simple list
fruits = ["apple", "banana", "cherry"]
print(fruits)
2. Accessing Elements
fruits = ["apple", "banana", "cherry"]
# Accessing by index
print(fruits[0]) # First element: "apple"
print(fruits[-1]) # Last element: "cherry"
3. Modifying a List
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # Replace "banana" with "blueberry"
print(fruits) # ["apple", "blueberry", "cherry"]
4. Adding Elements
# Using append()
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits) # ["apple", "banana", "cherry"]
# Using insert()
fruits.insert(1, "blueberry")
print(fruits) # ["apple", "blueberry", "banana", "cherry"]
5. Removing Elements
fruits = ["apple", "banana", "cherry"]
# Using remove()
fruits.remove("banana")
print(fruits) # ["apple", "cherry"]
# Using pop()
last_item = fruits.pop()
print(last_item) # "cherry"
print(fruits) # ["apple"]
# Using del
del fruits[0]
print(fruits) # []
6. Slicing a List
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Get a sublist
print(fruits[1:4]) # ["banana", "cherry", "date"]
# Reverse a list
print(fruits[::-1]) # ["elderberry", "date", "cherry", "banana", "apple"]
8. List Comprehension
# Create a list of squares
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
9. Sorting a List
numbers = [5, 2, 9, 1]
# Ascending
numbers.sort()
print(numbers) # [1, 2, 5, 9]
# Descending
numbers.sort(reverse=True)
print(numbers) # [9, 5, 2, 1]
# Using sorted()
print(sorted(numbers)) # [1, 2, 5, 9]
# Index of an item
print(fruits.index("cherry")) # 2