A list in Python is a collection of items that are:
Lists are one of the most flexible and commonly used data structures in Python.
0).-1, -2, etc.[start:stop:step].append(), insert(), remove(), pop(), sort(), reverse(), etc.You define a list using square brackets [] and separate items with commas.
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(type(fruits))
Here, fruits is a list containing three string items. The type() function confirms that its type is list.
You can access items in a list by index. Indexing starts at 0. Negative indices start from the end.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
Slicing lets you extract a range of items from a list using the syntax list[start:stop:step].
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[::2]) # [0, 2, 4]
If you leave out start, Python assumes the beginning of the list. If you leave out stop, it assumes the end. The step controls how many items to skip each time.
Lists are mutable, which means you can change individual elements or modify the list length.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
fruits.append("orange")
fruits.remove("apple")
print(fruits)
Common list methods include:
append(x) – add an item x at the end.insert(i, x) – insert x at index i.remove(x) – remove the first occurrence of x.pop(i) – remove and return the item at index i (last item if index omitted).sort() – sort the list in ascending order.reverse() – reverse the order of the list.
nums = [3, 1, 4, 2]
nums.sort()
print(nums) # [1, 2, 3, 4]
Use a list when you need:
If you run the basic list example:
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(type(fruits))
You will see output like:
['apple', 'banana', 'cherry']
<class 'list'>
The first line prints the list contents. The second line confirms that fruits is an object of type list.
[:] to copy a list without affecting the original.len() to quickly find the number of items in a list.tuple instead of a list.