Lists: Operations & Methods
What is a list?
A list is an ordered, mutable collection of items written in square brackets [ ] and separated by commas. Items can be of any type, even other lists. Think of a list as a row of numbered lockers: each locker has an index and you can change what is inside.
Creating lists
marks = [78, 92, 65, 88]
mixed = ['Riya', 16, 5.4, True]
empty = []
from_range = list(range(1, 6))
from_text = list('hey')
print(marks, mixed, empty)
print(from_range, from_text)Indexing, slicing and changing items
Indexing and slicing work exactly like strings. The big difference: lists are mutable, so you can change an item by assigning to its index.
L = [10, 20, 30, 40, 50] print(L[0], L[-1], L[1:4], L[::-1], len(L)) L[2] = 35 # lists are mutable print(L)
List operations
L = [10, 20, 35, 40, 50] print([1, 2] + [3, 4]) # concatenation print([0] * 5) # repetition print(30 in L, 35 in L) # membership
Traversing a list
marks = [56, 78, 91, 45, 83]
for m in marks: # by value
print(m, end=' ')
print()
for i in range(len(marks)): # by index – needed to change items
marks[i] = marks[i] + 2 # grace marks
print(marks)Changing the loop variable m in for m in marks does not change the list. To modify items, loop over indexes with range(len(marks)).
List methods
m = [45, 12, 78, 34] m.append(90); print(m) # add at end m.insert(1, 60); print(m) # add at position 1 m.extend([5, 8]); print(m) # add many items print(m.pop(), m) # remove last, return it print(m.pop(0), m) # remove at index 0 m.remove(78); print(m) # remove first 78 print(m.index(34), m.count(12))
L = [1, 2] L.remove(5)
| Method | Action | Returns |
|---|---|---|
| append(x) | Add x at the end | None |
| insert(i, x) | Add x at index i | None |
| extend(seq) | Add every item of seq | None |
| pop(i) | Remove item at i (default last) | the removed item |
| remove(x) | Remove first x | None (ValueError if absent) |
| index(x) | Position of first x | int |
| count(x) | How many x | int |
| sort(), sort(reverse=True) | Sort in place | None |
| reverse() | Reverse in place | None |
| clear() | Remove all items | None |
Built-in functions and sort vs sorted
m = [60, 12, 34, 90, 5] m.sort(); print(m) m.sort(reverse=True); print(m) m.reverse(); print(m) print(len(m), max(m), min(m), sum(m)) n = [3, 1, 2] print(sorted(n), n) # sorted() gives a NEW list print(n.sort()) # sort() changes n and returns None del n[0]; print(n)
Taking a list as input
n = int(input('How many numbers? '))
nums = []
for i in range(n):
nums.append(int(input('Enter number: ')))
print('List:', nums)
print('Sum =', sum(nums), '| Average =', sum(nums) / n)
print('Largest =', max(nums), '| Smallest =', min(nums))Short cut when the user types numbers separated by spaces: nums = [int(x) for x in input().split()].
List comprehension
A list comprehension builds a new list in one line: [expression for item in sequence if condition].
nums = [12, 7, 30, 15, 8, 21, 4]
even = [x for x in nums if x % 2 == 0]
odd = [x for x in nums if x % 2 != 0]
squares = [x * x for x in range(1, 6)]
print('Even:', even, '| Odd:', odd)
print('Squares:', squares)Summary & practice
- List = ordered, mutable, in
[ ]; items of any type. - Indexing/slicing like strings;
L[i] = xchanges an item. - Add: append, insert, extend. Remove: pop, remove, del, clear.
sort()in place vssorted()new list.
Predict: L = [5, 3, 8]; L.append([1, 2]); print(len(L)) → ? L = [5, 3, 8]; L.extend('ab'); print(L) → ? Write a program to count how many numbers in a list are greater than the average.
Answers: 4; [5, 3, 8, 'a', 'b']
