Arrays in Python: Lists

Lists are mutable sequences that can hold any data type, defined with square brackets []. Elements are comma-separated and indexed from 0.

Creating Lists

1. Using Square Brackets

code.python
>>> a = []  # Empty list
>>> a = [1, 2, 3, 4, 5]  # List of numbers
>>> a = ['excel', 'python', 'world']  # List of strings
>>> a = [1, 5, 'b', False]  # Mixed data types
>>> a = [[1], [2], 3, 'four']  # Nested lists

2. Using the list() Function

Convert iterable objects (strings, ranges, tuples, etc.) to lists:

code.python
>>> a = list()  # Empty list
>>> a = list('hello')  # Convert string: ['h', 'e', 'l', 'l', 'o']
>>> a = list(range(8))  # Convert range: [0, 1, ..., 7]
>>> a = list((1, 'abc', True))  # Convert tuple: [1, 'abc', True]
>>> a = list({'San Zhang': 89, ';Si Li': 92})  # Convert dict: ['San Zhang', 'Si Li']
>>> a = list({1, 'abc', 123, 'hi'})  # Convert set: [1, 123, 'hi', 'abc']

3. Basic Operations

Length: len(a)

Count occurrences: a.count(2)

Membership: 1 in [1, 2, 3] (True), 4 not in [1, 2, 3] (True)

Traversal:

code.python
>>> for i in range(6): print(i)  # Range traversal
>>> for ad in ['Beijing', 'Shanghai', ';Guangzhou']: print(ad)  # List traversal

Indexing and Slicing

Indexing: Access elements by index (0-based). Negative indices count from the end (-1 = last element).

code.python
>>> ls = ['a', 'b', 'c']
>>> ls[2]  # 'c' (3rd element)
>>> ls[-2]  # 'b' (2nd class="text-secondary">from end)

Slicing: Extract sublists with start:end:step (excludes end). Omitting parameters defaults to start=0, end=last, step=1.

code.python
>>> a = [1, 2, 3, 4, 5]
>>> a[2:]  # [3, 4, 5] (class="text-secondary">from index 2 to end)
>>> a[:2]  # [1, 2] (class="text-secondary">from start to index 1)
>>> a[1:4]  # [2, 3, 4] (indices 13)
>>> a[::-1]  # [5, 4, 3, 2, 1] (reverse)

Adding List Elements

append(): Add to the end (fast).

code.python
>>> a = [1, 2, 3, 4]
>>> a.append(5)  # [1, 2, 3, 4, 5]

extend(): Add multiple elements (e.g., from another list, string, or range).

code.python
>>> a = [1, 2, 3, 4]
>>> a.extend([5, 6])  # [1, 2, 3, 4, 5, 6]
>>> a.extend('abc')  # [1, 2, 3, 4, 'a', 'b', 'c']

Operators: + (concatenate), * (repeat).

code.python
>>> [1, 2, 3] + [4, 5, 6]  # [1, 2, 3, 4, 5, 6]
>>> [1, 'a'] * 3  # [1, 'a', 1, 'a', 1, 'a']

Inserting List Elements

Use insert(index, element) to insert at a specific position:

code.python
>>> a = [1, 2, 3, 4]
>>> a.insert(3, 5)  # Insert 5 at index 3 → [1, 2, 3, 5, 4]

Deleting List Elements

pop(index): Remove element at index (default: last).

code.python
>>> a = [1, 2, 3, 4, 5, 6]
>>> a.pop()  # Remove last → [1, 2, 3, 4, 5]
>>> a.pop(2)  # Remove index 2 → [1, 2, 4, 5]

del: Delete element by index.

code.python
>>> a = [1, 2, 3, 4, 5, 6]
>>> del a[3]  # [1, 2, 3, 5, 6]

remove(element): Remove first occurrence of element.

code.python
>>> a = [1, 2, 3, 4, 5, 6]
>>> a.remove(3)  # [1, 2, 4, 5, 6]

Removing Duplicates from List Elements

Create a new list and add elements from the original list only if they are not already present:

code.python
>>> a = [1, 2, 3, 4, 3, 1]
>>> b = []
>>> for i in a:
... if i not in b:
... b.append(i)
... 
>>> b  # [1, 2, 3, 4]

Sorting List Elements

sort(): Sort in-place (default: ascending). Use reverse=True for descending.

code.python
>>> ls = [4, 2, 1, 3]
>>> ls.sort()  # [1, 2, 3, 4]
>>> ls.sort(reverse=True)  # [4, 3, 2, 1]

sorted(): Return a new sorted list (original unchanged).

code.python
>>> ls = [4, 2, 1, 3]
>>> a = sorted(ls)  # [1, 2, 3, 4]
>>> a = sorted(ls, reverse=True)  # [4, 3, 2, 1]

Calculating List Elements

Use built-in functions or NumPy for statistics:

code.python
>>> a = range(11)  # 0–10
>>> max(a)  # 10
>>> min(a)  # 0
>>> sum(a)  # 55
# Using NumPy
>>> class="text-secondary">import numpy class="text-secondary">as np
>>> np.amax(a)  # 10
>>> np.mean(a)  # 5.0
>>> np.median(a)  # 5.0

Splitting and Merging Lists

Split: Use split(separator) on strings (returns a list).

code.python
>>> a = 'Where are you class="text-secondary">from'
>>> a.split()  # ['Where', 'are', 'you', 'class="text-secondary">from'] (default: space)

Merge: Use separator.join(list) to concatenate strings.

code.python
>>> a = ','
>>> b = ['hello', 'abc', 'python']
>>> a.join(b)  # 'hello,abc,python'

Filtering Lists

List comprehension:

code.python
>>> a = range(9)  # 0–8
>>> b = [i for i in a if i > 3]  # [4, 5, 6, 7, 8]

filter(): Use with a lambda function.

code.python
>>> a = range(9)
>>> b = filter(lambda i: i > 3, a)
>>> list(b)  # [4, 5, 6, 7, 8]

Two-Dimensional Lists

Create with nested lists (e.g., [[1, 2, 3], [4, 5, 6]]). Indexing uses [row][column]:

code.python
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a[2]  # 6(2nd row, 3rd column)
>>> a[1]  # [4, 5, 6] (entire 2nd row)
>>> a[1:2]  # [[4, 5, 6]] (slice of rows 11)

Exchanging Data Between Excel Worksheets and Lists

Use xlwings to read/write lists:

Read from Excel:

code.python
>>> class="text-secondary">import xlwings class="text-secondary">as xw
>>> bk = xw.Book()
>>> sht = bk.sheets(1)
>>> lst = sht.range('B2:D2';).value  # Row data: [1.0, 2.0, 3.0]
>>> lst2 = sht.range('B2:B4';).value  # Column data: [1.0, 4.0, 7.0]
>>> lst3 = sht.range('B2:D4';).value  # Range data: [[1.0, 2.0, 3.0], ...]

Write to Excel:

code.python
>>> lst = [1, 2, 3, 4, 5]
>>> sht.range('A1').value = lst  # Write 1D list to row
>>> lst_col = [[1], [2], [3]]
>>> sht.range('C1').value = lst_col  # Write 2D list to column
>>> sht.range('E1').options(transpose=True).value = lst  # Transpose 1D to column

7.2.13–7.2.16 Examples (Python Implementations)

Similar to Excel VBA examples (student grades, highlighting duplicates, finding minimum greater than a value, Pascal's Triangle), but using Python lists and xlwings. Code is provided in the original document (e.g., sam07-01.py to sam07-04.py).