Python Lists

Ordered, mutable, heterogeneous โ€” the workhorse data structure. Creating, indexing/slicing, editing, adding, deleting, operators, functions, and three coding exercises.

Overview

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:

  1. What is a List
  2. List vs Array
  3. Create
  4. Access
  5. Edit
  6. Add
  7. Delete
  8. Operations
  9. Functions

Key Concepts / Properties

1. List vs Array

FeatureArray (C / Java)Python List
Data homogeneityHomogeneous โ€” all items must be the exact same typeHeterogeneous โ€” can hold mixed types in the same list
Memory allocationContiguous โ€” stored in consecutive memory addressesReferential โ€” stores pointers/references to object memory locations
Execution speedFaster โ€” adjacent memory layout speeds up numerical computationSlower โ€” reference lookups add minor overhead
Flexibility & sizingFixed size upon declarationDynamic โ€” 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.

2. Creating Lists

Empty list

# Method 1: square brackets
l1 = []

# Method 2: list() constructor
l2 = list()

print(l1, l2)   # Output: [] []

Homogeneous list

numbers = [1, 3, 4, 5, 6]

Heterogeneous list (mixed data types)

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.

Multi-dimensional Lists

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]]]

Creating a list from a string using list()

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.

3. Accessing List Elements (Indexing & Slicing)

Python lists use zero-based indexing and follow the same syntax as Python strings.

Given:

sample_list = ["apple", "banana", "cherry", "date"]
OperationCodeResultExplanation
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 listsample_list[::-1]reversed listStep of -1 reverses order

Slicing syntax: list[start : end : step]

Accessing elements in nested (2D) lists

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

Accessing elements in nested (3D) lists

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.

4. Editing List Elements

Lists in Python are mutable โ€” you can change their contents after creation.

Single item modification

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]

Slice assignment (replacing multiple elements at once)

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.

5. Adding Elements to a List

Python provides three built-in methods: append(), extend(), insert().

append(item) โ€” adds a single element to the end

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]]

extend(iterable) โ€” unpacks and appends each item individually

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.

insert(index, item) โ€” inserts an item at a specific position

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:

6. Deleting Items from a List

Python provides four options for removing items: del, remove(), pop(), clear().

del โ€” deletes by index, by slice, or deletes the variable entirely

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 with del, the variable no longer exists and referencing it raises a NameError.
โš ๏ธ Watch out for stray quotes when indexing (e.g. a misplaced ' inside del L[-4]) โ€” this can trigger a SyntaxError: EOL while scanning string literal.

remove(value) โ€” removes the first occurrence of a specified value

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.

pop(index) โ€” removes and returns an item; defaults to the last item

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).

clear() โ€” empties the list completely

l = [1, 3, 4, 5]
l.clear()
print(l)
# Output: []

7. List Operations

Given:

L = [1, 2, 3, 4]
L1 = [5, 6, 7, 8]

Concatenation with +

L + L1
# Output: [1, 2, 3, 4, 5, 6, 7, 8]
Creates a new list; L and L1 themselves remain unchanged.

Repetition with *

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.

Iteration with for

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

Membership testing with in / not in

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.

8. List Functions

Given:

L = [1, 2, 3, 4]
FunctionExampleResultPurpose
len()len(L)4Number of elements
min()min(L)1Smallest value
max()max(L)4Largest 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 NoneModifies the original list
L.sort(reverse=True)L.sort(reverse=True)Sorts in place, descendingModifies the original list
L.index(value)L.index(3)2Index of the first occurrence of a value
sorted() vs .sort():

9. Coding Exercises

Exercise 1 โ€” Remove duplicates, preserving order

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).

Exercise 2 โ€” Custom Title Case (capitalize each word, without .title())

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:

  1. .split() breaks the sentence into a list of words.
  2. .capitalize() capitalizes the first letter of each word.
  3. " ".join(...) merges the list back into a single string, with spaces between words.

Exercise 3 โ€” Extract username/prefix from an email/URL before @

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.

โš ๏ธ Note: if the string has no @ (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.

Things to Remember

Quick Revision

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:

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.