Ordered, mutable, heterogeneous โ the workhorse data structure. Creating, indexing/slicing, editing, adding, deleting, operators, functions, and three coding exercises.
A List is one of Python's built-in sequence data types used to store a collection of items (multiple values) under a single variable name. Unlike arrays in other languages, Python lists are heterogeneous (can hold different data types together) and are more flexible/programmer-friendly, though slightly slower than arrays.
Topics covered in this note:
None, complex numbers).[].| Feature | Array (C / Java) | Python List |
|---|---|---|
| Data homogeneity | Homogeneous โ all items must be the exact same type | Heterogeneous โ can hold mixed types in the same list |
| Memory allocation | Contiguous โ stored in consecutive memory addresses | Referential โ stores pointers/references to object memory locations |
| Execution speed | Faster โ adjacent memory layout speeds up numerical computation | Slower โ reference lookups add minor overhead |
| Flexibility & sizing | Fixed size upon declaration | Dynamic โ items can be added/removed freely |
Key revision point: C/Java arrays store actual raw values contiguously, whereas Python lists store references (memory addresses) to objects scattered in memory. This referential design is why lists can be heterogeneous but arrays cannot.
# Method 1: square brackets
l1 = []
# Method 2: list() constructor
l2 = list()
print(l1, l2) # Output: [] []
numbers = [1, 3, 4, 5, 6]
mixed_list = [1, 2.5, "Hello", True, None, 5+6j]
print(mixed_list)
# Output: [1, 2.5, 'Hello', True, None, (5+6j)]
A single list can hold an int, float, string, boolean, None, and even a complex number together โ this is what makes Python lists heterogeneous.
2D list (a list containing another list as an element):
matrix_2d = [1, 2, [3, 5]]
3D list (a list of lists of lists):
matrix_3d = [[[1, 4], [3, 5]], [[6, 7], [8, 9]]]
L5 = list("Haldia")
print(L5)
# Output: ['H', 'a', 'l', 'd', 'i', 'a']
list() breaks a string into its individual characters and stores each as a separate list item.
Python lists use zero-based indexing and follow the same syntax as Python strings.
Given:
sample_list = ["apple", "banana", "cherry", "date"]
| Operation | Code | Result | Explanation |
|---|---|---|---|
| First element (positive indexing) | sample_list[0] | 'apple' | Indexing starts at 0 |
| Last element (negative indexing) | sample_list[-1] | 'date' | Negative indexing counts back from -1 |
| Slice (index 1 to 2) | sample_list[1:3] | ['banana', 'cherry'] | Stop index is exclusive |
| Reverse the list | sample_list[::-1] | reversed list | Step of -1 reverses order |
Slicing syntax: list[start : end : step]
start โ inclusive start index (default 0)end โ exclusive end index (stops at end - 1)step โ increment size (default 1)Rule of thumb: index from the outermost list inward, step by step.
L3 = [1, 2, 3, [4, 5]]
L3[0] # 1
L3[-1] # [4, 5] โ the whole nested list
L3[-1][0] # 4 โ first element of the nested list
L3[-1][-1] # 5 โ last element of the nested list
You can also assign a nested list to a variable and index it separately:
x = L3[-1] # x = [4, 5]
x[0] # 4
L4 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
L4[1][1][0] # 7 โ 2nd outer list โ 2nd inner list โ 1st element
L4[0][1][1] # 4 โ 1st outer list โ 2nd inner list โ 2nd element
Tip: For nested lists, read the indices left to right โ each index "drills down" one level deeper into the structure. To access an element inside an n-dimensional list, chain n sets of square brackets.
Lists in Python are mutable โ you can change their contents after creation.
L = [1, 2, 3, 4, 5]
L[0] = 100
print(L)
# Output: [100, 2, 3, 4, 5]
L[-1] = 500
print(L)
# Output: [100, 2, 3, 4, 500]
L[1:4] = [200, 300, 400]
print(L)
# Output: [100, 200, 300, 400, 500]
This replaces elements from index 1 up to (but not including) index 4 with the new list of values.
Python provides three built-in methods: append(), extend(), insert().
l = [1, 2, 3]
l.append(4)
print(l)
# Output: [1, 2, 3, 4]
Note: append() adds a whole object โ including another list โ as a single (nested) element, it does not merge it in:
l.append([6, 7])
print(l)
# Output: [1, 2, 3, 4, [6, 7]]
l = [1, 2, 3]
l.extend([5, 6])
print(l)
# Output: [1, 2, 3, 5, 6]
l.extend("goa")
print(l)
# Output: [..., 'g', 'o', 'a']
# Each character of the string is added as a separate element
append vs extend:append()adds its argument as a single element (even if it's a list);extend()unpacks the argument and adds each item individually.
l = [1, 2, 3]
l.insert(1, 20) # insert 20 at index 1
print(l)
# Output: [1, 20, 2, 3]
Existing elements shift to the right to make room.
Summary:
append() โ adds 1 item at the end.extend() โ unpacks and appends multiple items at the end.insert() โ adds 1 item at a specified index.Python provides four options for removing items: del, remove(), pop(), clear().
l = [1, 2, 3, 4, 5]
del l[0] # deletes item at index 0
print(l) # Output: [2, 3, 4, 5]
del l[1:3] # deletes a slice
print(l) # Output: [2, 5]
del L2
print(L2)
NameError: name 'L2' is not defined
Once deleted withdel, the variable no longer exists and referencing it raises aNameError.
' inside del L[-4]) โ this can trigger a SyntaxError: EOL while scanning string literal.l = ["python", "java", "c++", "java"]
l.remove("java")
print(l)
# Output: ['python', 'c++', 'java']
Removes by value, not by index. If the value appears multiple times, only the first occurrence is removed.
l = [100, 200, 300, 400]
last_item = l.pop()
print(last_item) # Output: 400
print(l) # Output: [100, 200, 300]
item = l.pop(1)
print(item) # Output: 200
print(l) # Output: [100, 300]
Useful when you need the removed value for further use (e.g., stack-like behavior).
l = [1, 3, 4, 5]
l.clear()
print(l)
# Output: []
Given:
L = [1, 2, 3, 4]
L1 = [5, 6, 7, 8]
L + L1
# Output: [1, 2, 3, 4, 5, 6, 7, 8]
Creates a new list;LandL1themselves remain unchanged.
L * 3
# Output: [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
Repeats the entire list's contents the given number of times.
for item in L:
print(item)
# Output: 1 2 3 4
For a nested list, for iterates over the top-level elements only:
L3 = [1, 2, 3, [4, 5]]
for i in L3:
print(i)
# Output:
# 1
# 2
# 3
# [4, 5] โ printed as a whole nested list, not unpacked
numbers = [10, 20, 30]
print(20 in numbers) # True
print(100 not in numbers) # True
4 in L3 # False โ 4 is inside the nested sublist, not top-level
[4, 5] in L3 # True โ the nested list itself is a top-level element
Key takeaway: in checks only the top level of the list โ it does not automatically search inside nested sublists.
Given:
L = [1, 2, 3, 4]
| Function | Example | Result | Purpose |
|---|---|---|---|
len() | len(L) | 4 | Number of elements |
min() | min(L) | 1 | Smallest value |
max() | max(L) | 4 | Largest value |
sorted() | sorted(L) | [1, 2, 3, 4] | Returns a new sorted list (original unchanged) |
sorted(reverse=True) | sorted(L, reverse=True) | [4, 3, 2, 1] | Sorted descending, new list |
L.sort() | L.sort() | Sorts in place, returns None | Modifies the original list |
L.sort(reverse=True) | L.sort(reverse=True) | Sorts in place, descending | Modifies the original list |
L.index(value) | L.index(3) | 2 | Index of the first occurrence of a value |
sorted() vs .sort():
sorted(L)is a built-in function โ returns a new list, leavesLunchanged.L.sort()is a list method โ sortsLin place and modifies the original list directly.
input_list = [1, 1, 2, 2, 3, 3, 4, 4]
unique_list = []
for item in input_list:
if item not in unique_list:
unique_list.append(item)
print(unique_list)
# Output: [1, 2, 3, 4]
Logic: Loop through each item; only add it to the new list if it isn't already present (checked with in).
sample_text = "hello world python programming"
words_list = sample_text.split()
capitalized_words = []
for word in words_list:
capitalized_word = word.capitalize()
capitalized_words.append(capitalized_word)
result_string = " ".join(capitalized_words)
print("Title Case Text:", result_string)
# Output: Hello World Python Programming
Logic:
.split() breaks the sentence into a list of words..capitalize() capitalizes the first letter of each word." ".join(...) merges the list back into a single string, with spaces between words.Approach A โ split("@"):
email = "campusx_tutor@gmail.com"
parts = email.split("@")
username = parts[0]
print("Username:", username)
# Output: campusx_tutor
split("@") separates the string into parts at @; index [0] gives the part before it.
Approach B โ find() and slicing:
sample = "nitish.com"
print(sample[:sample.find("@")])
find("@") returns the index of @ (or -1 if not found); slicing [:index] takes everything before it.
@ (as in "nitish.com"), find() returns -1, so double-check with an actual @-containing string when testing.Approach C โ manual loop with break:
string = "nitish.com"
for i in range(0, len(string)):
if string[i] == '@':
break
else:
print(string[i], end="")
Logic: Loop through each character; stop (break) if @ is found, otherwise print each character without a newline (end="") to build the prefix character by character.
append() adds as a single (possibly nested) element; extend() unpacks and adds each item individually.del can remove by index, by slice, or delete the variable entirely.remove() deletes by value; pop() removes and returns an item (last, by default, or a given index).in and for only operate at the top level for nested lists โ they don't auto-flatten nested structures.sorted() โ new list (function); .sort() โ in-place (method)..capitalize(), .split(), .join(), and .find() are frequently combined with lists for string-processing exercises.Python lists ([]) store ordered, mutable, heterogeneous, dynamically-sized data โ unlike arrays, which are contiguous, fixed-size, and homogeneous. Create lists directly (L = [1,2,3]), from a string (list("abc")), or empty ([] / list()). Lists can be nested to form 2D/3D structures, accessed via chained indices like L4[1][1][0].
CRUD summary:
[], list(), list("string")L[i], negative indexing L[-1], slicing L[a:b], reverse L[::-1]L[i] = x or slice assignment L[a:b] = [...] (lists are mutable)append() (single item), extend() (unpack iterable), insert(index, value)del L[i], remove(value), pop() (returns removed value), clear()Operations: + concatenates, * repeats, for iterates top-level items, in checks top-level membership.
Functions: len(), min(), max(), sorted() (new list) vs .sort() (in-place), .index(value).
Practiced through 3 coding exercises: removing duplicates, custom title-casing a sentence, and extracting a username/prefix before @ using split(), find(), or a manual loop with break.