Lists — Mutable Sequences

লিস্ট — পরিবর্তনযোগ্য sequence, Python-এর workhorse

Read: ~35 min Intermediate 5 practice problems Live code runner

1. What Is a List?

A Python list is an ordered, mutable sequence of arbitrary values. Internally it's a dynamic array that grows as you add items. Lists are the most-used data structure in Python — from shopping carts to matrix rows to batches of images.

Python-এর list হলো একটি ordered এবং mutable sequence — এতে যেকোনো type-এর মান রাখা যায়, এবং আইটেম যোগ-বিয়োগ করা যায়। অভ্যন্তরে এটি একটি dynamic array।

2. Creating & Accessing Lists

create.py
empty  = []
fruits = ["apple", "mango", "banana"]
mixed  = [1, "two", 3.0, True, None]
nested = [[1, 2], [3, 4]]

print(fruits[0])           # apple
print(fruits[-1])          # banana
print(fruits[1:])          # ['mango', 'banana']
print(nested[0][1])        # 2
print(len(fruits))         # 3

3. Adding & Removing Items

List mutation methods append(x) — end insert(i, x) extend(iter) pop(i) — remove & return remove(x) clear() reverse() Figure 14.1 — Core mutation methods.
mutate.py
cart = ["rice", "salt"]
cart.append("oil")            # O(1) amortized
cart.extend(["sugar", "tea"]) # add each element
cart.insert(0, "onion")        # O(n) — shifts everything right
print(cart)

last = cart.pop()                # remove last → "tea"
cart.remove("rice")             # remove first occurrence
print(cart, "popped:", last)
Performance note: append is amortized O(1), but insert(0, x) is O(n) — it must shift every element. For a queue, use collections.deque for O(1) popleft/appendleft.

append দ্রুত; কিন্তু insert(0, x) ধীর (O(n))। Queue-এর জন্য collections.deque ব্যবহার করুন।

4. Sorting — .sort() vs sorted()

list.sort() sorts in place and returns None. sorted(iterable) returns a new sorted list and leaves the original untouched.

sort.py
nums = [5, 2, 9, 1, 7]

# in-place
nums.sort()
print(nums)                # [1, 2, 5, 7, 9]

nums.sort(reverse=True)
print(nums)                # [9, 7, 5, 2, 1]

# sorted — returns new list
words = ["delta", "alpha", "bravo"]
print(sorted(words))
print(sorted(words, key=len))    # by length
print(words)                         # original unchanged

5. Shallow vs Deep Copy

b = a does not copy; both names point to the same list. To copy, use a.copy(), list(a), a[:], or for nested lists, copy.deepcopy(a).

copy.py
import copy

a = [1, 2, 3]
b = a                  # same object!
b.append(99)
print(a)            # [1, 2, 3, 99] — a is affected

# shallow copy
c = a.copy()
c.append(100)
print(a)            # unchanged

# deep copy for nested
matrix = [[1, 2], [3, 4]]
shallow = matrix.copy()
shallow[0].append(999)
print(matrix)       # inner list was shared!

deep = copy.deepcopy(matrix)
deep[0].append(5555)
print(matrix)       # truly independent
b = a কপি করে না — দুটি নাম একই object-কে reference করে। Shallow copy শুধু বাইরের list কপি করে, ভেতরের list-গুলো shared থাকে। নেস্টেড structure-এর জন্য copy.deepcopy ব্যবহার করুন।

6. Lists as Stack & Queue

Using append + pop, a list works perfectly as a stack (LIFO).

stack_queue.py
# stack — LIFO
stack = []
stack.append("page1")
stack.append("page2")
stack.append("page3")
print(stack.pop())     # page3
print(stack.pop())     # page2

# queue — use deque for O(1)
from collections import deque
q = deque()
q.append("task1")
q.append("task2")
print(q.popleft())    # task1 — FIFO

7. Vocabulary

TermMeaningবাংলায়
MutableCan be modified after creation.তৈরির পরও পরিবর্তন করা যায়।
In-placeMutation without creating a new object.নতুন object না বানিয়ে পরিবর্তন।
Amortized O(1)Average-case constant time over many ops.গড়পড়তা O(1)।
Shallow copyCopies outer container only.শুধু বাইরের container কপি।
Deep copyRecursively copies every nested object.প্রতিটি nested object পর্যন্ত কপি।
StackLIFO — last in, first out.LIFO — শেষে ঢোকা প্রথমে বের হয়।
QueueFIFO — first in, first out.FIFO — প্রথমে ঢোকা প্রথমে বের হয়।

8. Practice Problems

  1. Remove duplicates from a list while preserving order.
    List থেকে duplicate বাদ দিন, কিন্তু order যেন বজায় থাকে।
    ✨ Show Answer
    ans1.py
    def dedup(xs):
        seen = set()
        out = []
        for x in xs:
            if x not in seen:
                seen.add(x)
                out.append(x)
        return out
    
    print(dedup([3, 1, 3, 2, 1, 4]))
  2. Find the second largest number in a list.
    একটি list-এর দ্বিতীয় বৃহত্তম সংখ্যা বের করুন।
    ✨ Show Answer
    ans2.py
    xs = [10, 5, 23, 8, 23, 19]
    unique = sorted(set(xs), reverse=True)
    print(unique[1])
  3. Rotate a list right by k positions.
    একটি list-কে ডান দিকে k position rotate করুন।
    ✨ Show Answer
    ans3.py
    def rotate(xs, k):
        n = len(xs)
        k = k % n
        return xs[-k:] + xs[:-k]
    
    print(rotate([1,2,3,4,5], 2))
  4. Why does sort() return None instead of the sorted list?
    sort() কেন sorted list-এর পরিবর্তে None return করে?
    ✨ Show Answer

    This is a deliberate Python convention: methods that mutate in place return None. It prevents accidental misuse like sorted_list = my_list.sort() — which would bind None and hide the mutation.

    Python-এর convention — যে method in-place mutate করে, তা None return করে। এটি new = my_list.sort()-এর মতো ভুল থেকে রক্ষা করে।

  5. Given prices = [100, 80, 120, 75, 90], compute the cumulative total at each step.
    প্রতিটি পদক্ষেপে cumulative যোগফল বের করুন।
    ✨ Show Answer
    ans5.py
    prices = [100, 80, 120, 75, 90]
    running = []
    total = 0
    for p in prices:
        total += p
        running.append(total)
    print(running)

Summary — Module 14

Lists are Python's primary mutable sequence. Create with [], add with append/extend/insert, remove with pop/remove. sort() mutates in place; sorted() returns a new list. Assignment does not copy — use a.copy(), a[:], or copy.deepcopy(). For efficient queues, reach for collections.deque.

List হলো Python-এর প্রধান mutable sequence। append দ্রুত, insert(0, x) ধীর। sort() in-place, sorted() নতুন list দেয়। Assignment কপি নয় — দরকারে .copy() বা deepcopy ব্যবহার করুন।

Next Module → Tuples & Sequences — immutable sibling of lists।