Note
Module Scope: This directory (8.List) contains 40 modernized Python scripts along with an automated test suite (test_list.py). All scripts are fully compatible across Python 3.3 through Python 3.13 while providing comparative historical context for Python 2.7 legacy behavior.
-
Python Version Modernization (3.3 – 3.13 & 2.7 Comparison):
- Modernized code formatting to PEP 8 standard with type hint support and explicit function returns.
- Refactored list operations: dynamic appending (
append), shallow copies (copy), in-place clearing (clear), multi-dimensional matrix lookups, Timsort algorithm demonstrations (sortvssorted), slicing step dynamics ([start:stop:step]), and key-based sorting withlambdaandoperator.attrgetter. - Corrected spellings across data structures (e.g.
Vegetable,Southampton,Manchester).
-
Comprehensive Unit Test Suite (test_list.py):
- Built an automated test suite using
unittestverifying all 40 scripts. - Achieved 100% test passage (40/40 tests passing in 0.002s).
- Built an automated test suite using
-
Documentation (docs.md):
- Detailed method analysis, time complexities (
$O(1)$ append vs$O(N)$ insertion/deletion), Python 3.3 – 3.13 evolutionary upgrades, and Python 2.7 legacy differences.
- Detailed method analysis, time complexities (
Python lists are dynamic arrays storing memory references to objects. They provide fast random access (
| Aspect | Python 2.7 Legacy | Python 3.3 – 3.13 Standard | Status in Workspace |
|---|---|---|---|
| Methods (.copy / .clear) | Missing (used lst[:] or del lst[:]) |
Built-in methods (.copy(), .clear()) |
Standardized Py3 methods |
| Heterogeneous Sorting | Allowed non-deterministic comparisons | Raises TypeError on unorderable types |
Modernized with type safety |
| Starred Unpacking | Syntax error | Supported (first, *rest = lst) |
Fully modernized |
| Test Suite Coverage | Manual script execution | Automated unittest runner (test_list.py) |
100% Pass Rate (40/40) |
- Lists are Mutable: You can modify list elements in-place (
lst[0] = 'new_value'). .sort()vssorted():.sort()changes the existing list in-place and returnsNone, whilesorted(iterable)leaves the original list untouched and returns a new sorted list.- Slicing:
lst[start:stop:step]lets you extract sub-lists or reverse a sequence usinglst[::-1].
-
Dynamic Array Resizing: CPython list capacity expands geometrically with growth factor
$\approx 1.125$ ($0, 4, 8, 16, 25, 35, 46, \dots$ ) to guarantee amortized$O(1)$ append complexity. -
Timsort Stability:
sort()uses Timsort ($O(N \log N)$ worst-case,$O(N)$ best-case), maintaining original element order for equal keys. -
Memory Footprint: Lists store pointers (8 bytes per reference on 64-bit platforms). For memory-dense numeric data, prefer
array.arrayornumpy.ndarray.
append_and_remove_from_the_list.py: Nested list management,.append(), and element removal via.remove().append_pop.py: LIFO stack simulation using.append()and.pop().append_to_list.py: Iterative list construction.ascending_order.py: Numerical ascending and descending sorting.books.py: Collection management, search, and alphabetical sorting.change_list.py: Element replacement by index and slice mutation.concatinat.py: Sequence concatenation using+and+=.delete.py: Deleting single items or slice ranges usingdel.drop_add.py: Queue operations combininginsert(0)andpop(0).enumerate_list.py: Tuple unpacking during iteration viaenumerate().example.py: Heterogeneous lists, length evaluation, and boundaries.extend_list.py: Contrast between.append()and.extend().footbal_teams.py: Advanced team sorting by name length and reverse sorting.for_list.py: Sequential element iteration.index_list.py: Positional lookups with.index()and range bounds.insert_to_line.py: In-place insertion at explicit positions.is_==.py: Value equality (==) vs memory identity (is).join_list.py: String joining from list elements usingstr.join().list_1.py: Basic list creation and element retrieval.list_func.py: Numerical aggregation (min,max,sum) and string to list conversion.list_func_1.py: Adding elements with.append()and.insert().list_func_2.py: List duplication (.copy()), index retrieval, sub-list insertion.list_func_3.py: Membership testing (in/not in) and string formatting.list_inside_list.py: Matrix manipulation and multi-dimensional index access.list_keys.py: Introspection of list class attributes usingdir().list_number.py: Statistical evaluations on integer sequences.more_list.py: Sequence concatenation and positional mutations.number.py: Comparison of in-place.sort()vs standardsorted().numbers.py: Slicing sequence reversal and range statistics.planets.py: Struct sorting withlambdakeys across tuple elements.reverse_list.py: Reversing lists in-place vs reverse sorting.reverse_url.py: Sequence reversal using[::-1]vsreversed()iterator.slicing_list.py: Advanced indexing with positive/negative steps.sort_str.py: String sequence sorting and immutability notes.sorted_list.py: Tokenization and word frequency mapping with dicts.sorted_not_sort.py: Immutable sequence sorting returning new lists.sorted_tuple_sort.py: Sorting tuples and string characters into lists.str_list.py: In-place character list reversal and sorting.students.py: Sorting custom class instances withlambdaandoperator.attrgetter.sum.py: List element summation, count, and average calculations.
Run the test suite from the terminal:
python3 -m unittest discover -s ~/PycharmProjects/Devel/Python/8.List -p "test_*.py"----------------------------------------------------------------------
Ran 40 tests in 0.002s
OK
| Feature / Operation | Python 3.3 Standard | Python 3.13 Standard | Code Context & Performance Impact |
|---|---|---|---|
Methods (.copy(), .clear()) |
Introduced as built-in list methods | Fully optimized C implementations | lst.copy(), lst.clear() in list_func_2.py and delete.py |
Unpacking ([*a, *b]) |
Required concatenation a + b or .extend() |
Generalized sequence unpacking (PEP 448) | Merging sequences in more_list.py and concatinat.py |
| Traceback Precision | Line-level IndexError callouts |
Fine-grained error locations pointing to exact index | Slicing and index lookups in index_list.py |
| Execution Speed | Standard CPython interpreter loop | 20-30% faster execution via CPython vectorcall specialization | In-place sorting and reversals in ascending_order.py |
| Comprehensions Inlining | Allocates function call frames | Inlined bytecode execution (PEP 709) | Matrix extraction & list comprehensions |
Warning
1. Heterogeneous List Sorting (Type Comparisons)
- Python 2.7: Allowed sorting lists containing mixed unorderable types (e.g.,
[1, 'apple', 3.14]). Sorting defaulted to comparing type names as strings, producing non-deterministic sort orders across platforms. - Python 3.3 – 3.13: Raises an explicit
TypeError: '<' not supported between instances of 'str' and 'int'if items are unorderable. - Script Relevance:
ascending_order.py,sort_str.py,number.py.
Warning
2. range() Memory Allocation vs xrange()
-
Python 2.7:
range(1000000)allocated a full list of 1,000,000 integer objects in memory.xrange()was mandatory for lazy iteration. -
Python 3.3 – 3.13:
range()returns an$O(1)$ lazy sequence generator object.list(range(...))must be explicitly invoked to construct a concrete list. -
Script Relevance:
for_list.py,numbers.py.
Warning
3. Extended Starred Unpacking (*rest)
- Python 2.7: Syntax like
first, *rest = [1, 2, 3, 4]produces aSyntaxError. Manual slicing was required:first, rest = lst[0], lst[1:]. - Python 3.3 – 3.13: Supported natively for unpacking sequence heads, tails, and mid-sections.
- Script Relevance:
slicing_list.py,list_func_2.py.
Note
4. List Copying & Clearing Methods (.copy(), .clear())
- Python 2.7:
.copy()and.clear()methods did not exist onlist. Copying requiredcopied = lst[:]orcopy.copy(lst), and clearing requireddel lst[:]. - Python 3.3 – 3.13: Built-in
lst.copy()andlst.clear()methods are standard. - Script Relevance:
list_func_2.py,delete.py,append_and_remove_from_the_list.py.
Note
5. print Statement vs Function Syntax
- Python 2.7: Used keyword statement
print my_listorprint my_list,(to omit trailing newline). - Python 3.3 – 3.13:
print()is a built-in function requiring parentheses:print(my_list, end=''). - Script Relevance: All 40 scripts in
8.List.