Python Docs
Python Lists — Full Notes
A list in Python is an ordered, changeable collection that can store multiple values. Lists allow duplicates and can contain any data type.
What Is a List?
Lists are created using square brackets and can store multiple items in a single variable.
Basic list creation:
mylist = ["apple", "banana", "cherry"]Printing a List
thislist = ["apple", "banana", "cherry"]
print(thislist)Lists Allow Duplicate Values
Because lists are indexed, they can store the same value multiple times.
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)Changing List Items
Lists are mutable, so you can update, delete, or add items after creation.
1. Change a Single Item
Modify any list element using its index.
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)2. Change a Range of Items
You can replace multiple values at once using slicing.
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)Insert More Items Than Replaced
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)Insert Fewer Items Than Replaced
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist)Insert Items
Use insert() to place an element at a specific index.
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)Adding Items
append()
Adds an item at the end of the list.
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)insert() at a Specific Position
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)extend() from Another List
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)extend() from Any Iterable
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)Python List Methods
Python provides several built-in methods to work efficiently with lists.
| Method | Definition |
|---|---|
| append() | Adds an element to the end of the list. |
| clear() | Removes all elements from the list. |
| copy() | Returns a shallow copy of the list. |
| count() | Counts how many times a value appears. |
| extend() | Appends items from another iterable. |
| index() | Returns index of first matching value. |
| insert() | Inserts an item at a specific position. |
| pop() | Removes and returns an element at index. |
| remove() | Removes the first matching value. |
| reverse() | Reverses the list in-place. |
| sort() | Sorts the list in ascending order. |