A list stores an ordered, changeable collection. Items can be any type, and duplicates are allowed.
fruits = ["apple", "mango", "banana"]
Access
fruits[0], fruits[-1], slices fruits[1:3], len(fruits), "mango" in fruits.
Change and add
fruits[1] = "kiwi"append(x)— add to the endinsert(i, x)— add at a positionextend(other_list)or+— join lists
Remove
remove(x)— first matching valuepop()— last item (returns it),pop(i)— item at indexdel fruits[0],clear()
Sort and search
sort()— sorts in place;sort(reverse=True);sort(key=len)sorted(list)— returns a new sorted listreverse(),index(x),count(x)
Useful functions
sum(), min(), max(), len(), any(), all().
Copying
b = a does not copy. Use a.copy() or a[:].
Example
Example — Shopping list
Python
cart = ["milk", "bread"]
cart.append("eggs")
cart.insert(0, "rice")
cart.extend(["tea", "sugar"])
print(cart)
cart.remove("bread")
last = cart.pop()
print("Removed:", last, "| Now:", cart)
prices = [45, 120, 30, 250]
print(sorted(prices), sum(prices), max(prices))
prices.sort(reverse=True)
print("Top 2:", prices[:2])
names = ["Zoya", "amit", "Ravi"]
print(sorted(names, key=str.lower))
Shows the growing list, "Removed: sugar", the sorted prices [30, 45, 120, 250], total 445, max 250, Top 2: [250, 120], and names sorted ignoring case: ['amit', 'Ravi', 'Zoya'].