A list in Python is an ordered, mutable (changeable) collection of items, enclosed in square brackets [ ].
- Lists can hold elements of different data types including numbers, strings, or even other lists.
Indexing and Slicing:
- Indexing is used to access individual elements using their position (starting at index 0).
- Slicing extracts a range of elements using start:stop syntax.
Example:
lst = [10, 20, 30, 40, 50]
print(lst[0]) # Output: 10
print(lst[1:3]) # Output: [20, 30]Changing Items:
Lists are mutable, so you can change their elements after creation.
Example:
lst[0] = 100
print(lst) # Output: [100, 20, 30, 40, 50]Adding and Removing Items:
- Use append() to add to the end.
- Use insert() to add at a specific position.
- Use remove() to delete a specific value.
- Use pop() to remove by index (or last item if no index is given).
Example:
lst.append(60)
lst.insert(1, 15)
lst.remove(30)
lst.pop(2)
print(lst) # Output might vary depending on operationsLooping Through a List:
Example:
for item in lst:
print(item)Copying Lists:
To avoid modifying the original list, use copy() or slicing.
Example:
new_lst = lst.copy()
# OR
new_lst = lst[:]List Comprehension:
A compact way to create lists from an iterable.
Example:
squares = [x*x for x in range(5)]
print(squares) # Output: [0, 1, 4, 9, 16]Sorting a List:
- Use sort() to sort the list in-place.
- Use sorted() to get a new sorted list.
Example:
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]Joining List Elements:
To join list elements into a string, use join() (only works with strings).
Example:
letters = ["a", "b", "c"]
result = ", ".join(letters)
print(result) # Output: a, b, c