---
# System prepended metadata

title: Chapter 7 - List and String
tags: [Computer programming]

---

---
slideOptions:
  theme: white
---

# Chapter 7 - List and String

###### tags: `Computer programming`

---

## Learning objectives
By the end of this chapter, you should be able to:
1. Distinguish between using sequences of variables and list
2. Access data in an element in a list and string
3. Use list and strings, and their corresponding methods
4. Describe the use of check data and the process of parity check

## List
To store a series of values in a program, there are two methods to complete this task.
1. **Method 1**: use 10 variables, with 10 identifiers, and need 10 statements to assign the values.
2. **Method 2**: use a list, just use 1 identifier and can assign all values by just a line.

![](https://i.imgur.com/bZkkiNO.jpg)


Lists are positionally ordered collections of values, and have no fixed size. 

### Using list in Python
Like using a variable, values are required to be assigned to a *list*, by using the square brackets (`[]`) and separated by commas, before use. A list can take *any data type*. Below shows the syntax to assign values to a list.
```python!
list_identifier = [values, (values, …)]
```

![](https://i.imgur.com/G0fYewY.jpg)


In Python, the list can include values with different data types, which is different from arrays in other programming languages. However, It is better to keep the same data type for easier understanding and code readability.

In Python, the list index always starts with 0.

#### Access data of an element

##### List index
Python uses an *index* to access the individual element in a list. For example,
```python!
score[0] = 42
```

The index can also be an integral value of a variable in Python, for example,
```python!
i = 5
score[i] = 12
```

We can use index in loop and selection, for example,

```python!
max = 0
for i in range(0, 5):
    if score[i] > max:
        max = score[i]

```

##### Negative indexing
Python allows negative indexing for the sequence. The index of -1 refers to the last item, -2 to the second last item, and so on. 

```python!
score[-3] = 13
```

![](https://i.imgur.com/VnHqDrI.jpg)


##### List slicing
In Python, we can access a range of elements in a list by using the slicing operator (`:`).

<iframe src="https://trinket.io/embed/python3/0dce87943a?runOption=run" width="100%" height="200" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

#### Exchange values within list
In Python, there are *two* methods to *swap values*. We can either
1.  directly *swap values* within a list by the default assignment, or 
2. *swap values* by using a temporary variable.

**Method 1**: directly swap values by assignment statement
We can just swap two values by their identifiers. The following example shows swapping values with the one assignment statement.
```python!
score[0], score[1] = score[1], score[0]
```

**Method 2**: swap values by using a temporary variable
Other programming languages, like C, do not support simultaneous assignment. We need to swap data by using a temporary variable, as shown below.

![](https://i.imgur.com/ObCdf8O.jpg)


### List and functions

List can be used in the inter-function communication. We can pass the list by either _passing individual elements_ or _pass the whole list_.

#### Pass individual elements

Passing individual elements is just like passing a variable.

![](https://i.imgur.com/MhLF5hW.jpg)

In Python, we can also pass the whole list to the function. The functions are required to define to accept the whole function, as shown below.

![](https://i.imgur.com/w2G6r8R.jpg)

As the list identifier is actually an _object_ (would be discussed in the later chapter), the array is actually passed by object reference.

### List methods

Below shows some methods that can be used for lists.

| **Methods** | **Meaning** |
| --- | --- |
| `list.append(x)` | Add element _x_ to the end of the list. |
| `list.sort()` | Sorts (orders) the list. |
| `list.reverse()` | Reverse the list. |
| `list.index(x)` | Returns index of first occurrence of _x_. |
| `list.insert(i,x)` | Inserts _x_ into list at index _i_. |
| `list.count(x)` | Returns the number of occurrences of _x_ in the list. |
| `list.remove(x)` | Deletes the first occurence of _x_ in list. |
| `list.pop(i)` | Deletes the _i_ th element of the list and returns its value. |

You may try out how to use the methods and test the result.

### List applications

Lists are usually used for calculating digits with specific algorithms. The following shows the calculation of checking digits of ISBN (International Standard Book Number).

#### Check digit of ISBN

ISBN is a series of numbers used to identify the books. Each book should have its own ISBN. The last digit of ISBN is used to check the result of the calculation of the first 12 algorithms with specific algorithm. The algorithm is like this, according to Wikipedia.

> The final character of a ten-digit International Standard Book Number is a check digit computed so that multiplying each digit by its position in the number (counting from the right) and taking the sum of these products modulo 11 is 0. The digit the farthest to the right (which is multiplied by 1) is the check digit, chosen to make the sum correct. It may need to have the value 10, which is represented as the letter X. For example, take the ISBN 0-201-53082-1: The sum of products is 0×10 + 2×9 + 0×8 + 1×7 + 5×6 + 3×5 + 0×4 + 8×3 + 2×2 + 1×1 = 99 ≡ 0 (mod 11). So the ISBN is valid. Note that positions can also be counted from left, in which case the check digit is multiplied by 10, to check validity: 0×1 + 2×2 + 0×3 + 1×4 + 5×5 + 3×6 + 0×7 + 8×8 + 2×9 + 1×10 = 143 ≡ 0 (mod 11).

Here is the pseudocode of the algorithm for calculating the check digit of a 13-digit ISBN in pseudocode (i.e. the code that is read by humans and no syntax is needed).

1. Initialise an integer array with size 12 and assign the ISBN digits to the array

2. Initialise another integer variable sum and assign 0 to it

3. For each element of the array
    If (index + 1) is an odd number
    Then sum = sum + array[index]
    Else if (index + 1) is an even array
    Then sum = sum + array[index] \* 3
    End for each loop

4. While the variable sum is a positive number
    sum = sum - 10
    End while

5. Print out the positive value of variable sum

We can convert the above pseudocode into a Python program, as shown below.

<iframe src="https://trinket.io/embed/python3/86996c39dd?runOption=run" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>


### 2D and multidimensional list

All the lists mentioned before are known as the _one-dimensional list_, i.e. known as a row or a column of values. We can also declare a _two-dimensional list_, as a _table_ of values with rows and columns.

![](https://i.imgur.com/Sc0LBp9.jpg)

For example, we need to create a 2D list in 5 rows and 3 columns with the following values.

![reference link](https://i.imgur.com/cumIbQM.jpg)

We can initialise the above 2D list with the following statement.

```python!
table = [
            [0, 1, 2],
            [10, 11, 12],
            [20, 21, 22],
            [30, 31, 32],
            [40, 41, 42],
        ]
```
#### Application - parity check

_Parity check_ is a method that checks the accuracy of transferred data by adding the string of binary code. There are two types of parity checks, namely _even parity bit_ and _odd parity bit_.

**Even parity bit** : the number of 1s including the check bit is even numbers

**Odd parity bit** : the number of 1s including the check bit is odd numbers

The following tables show some examples.

| **7 bits of data** | **(count of 1-bits)** | **8 bits including parity** |
| --- | --- | --- |
| **even** | **odd** |
| 0000000 | 0 | 0000000 **0** | 0000000 **1** |
| 1010001 | 3 | 1010001 **1** | 1010001 **0** |
| 1101001 | 4 | 1101001 **0** | 1101001 **1** |
| 1111111 | 7 | 1111111 **1** | 1111111 **0** |

We can find out whether the parity bit is preferred or not.

Besides from a string of data, the parity check can be used in the form of a table / 2D list, as shown below. Assume that even a parity check is used in the $7 \times 7$ list .

| 1 | 0 | 1 | 1 | 0 | 0 | **1** |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | 1 | 1 | 1 | 0 | 0 | **1** |
| 0 | 0 | 1 | 1 | 1 | 0 | **1** |
| 1 | 1 | 1 | 0 | 0 | 1 | **0** |
| 0 | 1 | 1 | 1 | 0 | 1 | **0** |
| 1 | 0 | 0 | 0 | 0 | 1 | **0** |
| **1** | **1** | **1** | **0** | **1** | **1** | **1** |

Can you write a Python program to check the 2D parity code?

### 3D list

Just like a 2D list, a 3D list can be considered as a cube. The following example shows a 3D list with 3 planes, 4 lows and 5 columns

![](https://i.imgur.com/7oX0kfi.jpg)

Another way to think of the 3D list is a 2D list with multiple layers.

![](https://i.imgur.com/uW0WACz.jpg)

## String

### Basic concept of string

A _string_ in Python is an object that stores _a sequence of characters_. You may imagine a string a the characters written on a line of horizontal _Genko yoshi_ (原稿紙), while there is _only one character_ in each box. Below shows an example of a string in Python.

![](https://i.imgur.com/0fDQ0f4.jpg)

### Using String in Python

Like a list, we can get the characters by the index and slice. The string formed by slicing is called a _substring_.

<iframe src="https://trinket.io/embed/python3/b8e2fac6bf?runOption=run" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

### String Representation

The string in Python is a sequence of characters. The character types include the alphabet like 'A', 'a', '0', '$'. The characters are stored in the form of ASCII (American Standard Code Information Interchange) encoding system(refer to Appendix 1). Each character is represented by an integer.

Python provides a couple of built-in functions that allow us to switch back and forth between characters and the numeric values used to represent them in strings. The ord function returns the numeric ("ordinal") code of a single character string, while chr goes the other direction. Below shows some examples.

| **Statement** | **Result** |
| --- | --- |
| `ord("a")` | 97 |
| `ord("A")` | 65 |
| `chr(97)` | 'a' |
| `chr(90)` | 'Z' |

### String methods

Below shows some methods of strings.

| **Method** | **Meaning** | **Example** | **Result** |
| --- | --- | --- | --- |
| `s.capitalize()` | Copy of s with only the first character capitalised | s = "hand some"s.capitalize() | "Hand some" |
| `s.center(width)` | Copy of s centred in a field of given _width_. | s = "Handsome"s.center(12) | " Handsome " |
| `s.count(sub)` | Count the number of occurrences of _sub_(substring) in s. | s = "apple"s.count("p") | 2 |
| `s.find(sub)` | Find the first position where _sub_ occurs in s. | s = "Handsome"s.find("some") | 4 |
| `s.join(list)` | Concatenate _list_ of strings into a new string, using s as separator. | s = ";"s.join(["A", "B"]) | "A;B" |
| `s.ljust(width)` | Like _center_, but s is left-justified. | s = "Handsome"s.ljust(12) | "Handsome " |
| `s.lower()` | Copy of s in all lowercase characters. | s = "Handsome"s.lower() | "handsome" |
| `s.lstrip()` | Copy of s with leading white space removed. | s = " Handsome "s.lstrip() | "Handsome " |
| `s.replace(oldsub, newsub)` | Replace all occurrences of _oldsub_ in s with _newsub_. | s = "Handsome"s.string("some",
"ling") | "Handling" |
| `s.rfind(sub)` | Like find, but returns the rightmost position. | s = "Apple"s.find("p") | 2 |
| `s.rjust(width)` | Like center, but s is right-justified. | s = "Handsome"s.rjust(12) | " Handsome" |
| `s.rstrip()` | Copy of s with trailing white space removed. | s = " Handsome "s.rstrip() | "Handsome" |
| `s.split()` | Split s into a list of substrings (see text). | s = "Hand some"s.split() | ["Hand", "some"] |
| `s.title()` | Copy of s with first character of each word capitalised. | s = "hand some"s.title() | "Hand Some" |
| `s.upper()` | Copy of s with all characters converted to uppercase. | s = "handsome"s.upper() | "HANDSOME" |

## Sequence Operations

Because list and strings are sequences, you know that all of the Python built-in sequence operations also apply to lists. To jog your memory here's a summary of those operations.

| **Operator** | **Meaning** |
| --- | --- |
| `sequence + sequence` | concatenation |
| `sequence * _int_exression` | repetition |
| `sequence[]` | indexing |
| `len(sequence)` | length |
| `sequence[:]` | slicing |
| `for variable in sequence:` | iteration |
| `expression in sequence` | Membership check (Returns a Boolean) |

## Chapter Summary

- Lists are used to store multiple items with different data types in a single variable.
- Python lists are similar to arrays in other programming languages.
- List items are ordered, changeable, and allow duplicate values.
- List items are indexed, the first item has index `[0]`.
- In inter-function communication, individual elements are passed by value, while the list object is passed by object reference.
- Strings are sequences of characters.
- Strings and list can be manipulated with the built-in sequence operations for concatenation (`+`), repetition (`*`), indexing (`[]`), slicing (`[:]`), and length (`len()`).
- String are represented in the computers as numeric codes. ASCII and Unicode are compatible standards that are used for specifying the correspondence between characters and the underlying codes. Python provides the `ord` and `chr` function for translating between Unicode codes and characters.

## Exercise

1. A list must contain at least one item.
 A. True
 B. False
 
2. ASCII is a standard for representing characters using numeric codes.
 A. True
 B. False
 
3. The method that adds a single item to the end of a list is
 A. extend
 B. add
 C. plus
 D. append
 
4. Which of the following is not a Python list method?
 A. index
 B. insert
 C. get
 D. pop

5. Which string method converts all the characters of a string to uppercase?
 A. capitalize
 B. capwords
 C. uppercase
 D. upper

6. Given the initial statements.  
    ```python!
    s1 = [2, 1, 4, 3]
    s2 = ['c', 'a', 'b']
    ```
    Show the result of evaluating each of the following sequence expressions.
      1. `s1 + s2`
      2. `3 * s1 + 2 * s2`
      3. `s1[1]`
      4. `s1[a:3]`
      5. `s1 + s2[-1]`


7. Given the initial statements.
    ```python!
    s1 = [2, 1, 4, 3]
    s2 = ['c', 'a', 'b']
    ```
    Show the values of s1 and s2 after executing each of the following statements. Treat each part independently (i.e. assume that `s1` and `s2` start with their original values each time).
      1. `remove(2)`
      2. `sort()`
      3. `append([s2.index['b'])`
      4. `pop(s1.pop(2))`
      5. `insert(s1[0], 'd')`

8. Given the initial statements.
    ```python!
    s1 = "spam"
    s2 = "ni!"
    ```
     Show the result of evaluating each of the following string expressions.
      1. `"The Knights who say, " + s2`
      2. `3 * s1 + 2 * s2`
      3. `s1[1]`
      4. `s1[1:3]`
      5. `s1[2] + s2[:2]`
      6. `s1 + s2[-1]`
      7. `upper()`
      8. `upper().ljust(4) * 3`

9. Given the initial statements.
    ```python!
    s1 = "spam"
    s2 = "ni!"
    ```
    Show a Python expression that could construct each of the following result by performing string operations on `s1` and `s2`.
      1. `"NI"`
      2. ` "Ni! Spamni!"`
      3. `"Spam Ni! Spam Ni! Spam Ni!"`
      4. `"Spam"`
      5. `["sp", "m"]`
      6. `"spm"`

## Programming Exercise

### Exercise 1

Write a tic-tac-toe program that allows two users to play tic-tac-toe. Use a 2D list to store the information of the tic-tac-toe board.

(Hint: you can input two values in one line as shown below)

<iframe src="https://trinket.io/embed/python3/9d2495d83a?runOption=run" width="100%" height="150" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

**Example** 

```
 . . .
 . . .
 . . .

O plays. Enter a coordinate (row column): 1 1

 . . .
 . O .
 . . .

 X plays. Enter a coordinate (row column): 0 2

 . . X
 . O .
 . . .

 O plays. Enter a coordinate (row column): 1 0

 . . X
 O O .
 . . .

 X plays. Enter a coordinate (row column): 0 1

 . X X
 O O .
 . . .

O plays. Enter a coordinate (row column): 1 2

 . X X
 O O O
 . . .

 O wins!
```

## Exercise 2

Write a program that generates 100 random integers between 0 to 9, stores them in a list, finds the frequency counts of each 0 to 9, and then prints a histogram for the 100 integers.

**Example:**

```
i count
0 7  *******
1 14 **************
2 11 ***********
3 9  *********
4 11 ***********
5 7  *******
6 11 ***********
7 9  *********
8 12 ************
9 9  *********
```

### Exercise 3

Repeat Exercise 2 but print the histogram in an upright diagram.

**Example:**
```
14 *
13 *
12 * *
11 * * * * *
10 * * * * *
 9 * * * * * * * *
 8 * * * * * * * *
 7 * * * * * * * * * *
 6 * * * * * * * * * *
 5 * * * * * * * * * *
 4 * * * * * * * * * *
 3 * * * * * * * * * *
 2 * * * * * * * * * *
 1 * * * * * * * * * *
 -----------------------
   0 1 2 3 4 5 6 7 8 9
```
### Exercise 4

Write a program that inputs a numeric check amount and writes the word equivalent of the amount.

**Example**: 

```
Enter the amount: 3217
THREE THOUSANDS TWO HUNDREDS and SEVENTEEN
 ```

### Exercise 5

Write a program that reads a sentence and reverse the words of the line.

(Hint: use `string.split`)

**Example**: 

```
Input: God does not play dice
Dice play not does God
```

### Exercise 6

An _acronym_ is a word formed by taking the first letter of the words in a phrase and making a word from them. For example, RAM is an acronym for "random access memory". Write a program that allows the user to type in a phrase and then outputs the acronym for that phrase.

_Note:_ The acronym should be all uppercase, even if the words in the phrase are not capitalised.

### Exercise 7

Numerologists claim to be able to determine a person's character traits based on the "numeric value" of a name. The value of a name is determined by summing up the values of the letters of the name where "a" is 1, "b" is 2, "c" is 3, up to "z" being 26. For example, the name "Zelle" would have the value 26 + 5 + 12 + 12 + 5 = 60.

Write a program that calculates the numeric value of a single name provided as input.

### Exercise 8

A Caesar cipher is a simple substitution cipher based on the idea of shifting each letter of the plaintext message to a fixed number (called the key) of positions in the alphabet. For example, if the key value is 2, the word "sourpuss" would be encoded as "Uqwtrwuu". The original message can be recovered by "reencoding" it using the negative of the key.

![](https://i.imgur.com/OB6kgxR.png)

Write a program that can encode and decode Caesar ciphers. The input to the program will be string of plaintext and the value of the key. The output will be an encoded message where each character in the original message is replaced by shifting it _key_ characters in the Unicode character set.

For example, if ch is a character in the string and key is the amount to shift, then the character that replaces ch can be calculated as: chr(ord(ch) + key).

## Appendix 1 - ASCII table

| No. | Char | No. | Char | No. | Char | No. | Char |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 0 | NUL | 32 | Space | 64 | @ | 96 | ` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 1 | SOH | 33 | ! | 65 | A | 97 | a |
| 2 | STX | 34 | " | 66 | B | 98 | b |
| 3 | ETX | 35 | # | 67 | C | 99 | c |
| 4 | EOT | 36 | $ | 68 | D | 100 | d |
| 5 | ENQ | 37 | % | 69 | E | 101 | e |
| 6 | ACK | 38 | & | 70 | F | 102 | f |
| 7 | BEL | 39 | ' | 71 | G | 103 | g |
| 8 | BS | 40 | ( | 72 | H | 104 | h |
| 9 | TAB | 41 | ) | 73 | I | 105 | i |
| 10 | LF | 42 | \* | 74 | J | 106 | j |
| 11 | VT | 43 | + | 75 | K | 107 | k |
| 12 | FF | 44 | , | 76 | L | 108 | l |
| 13 | CR | 45 | - | 77 | M | 109 | m |
| 14 | SO | 46 | . | 78 | N | 110 | n |
| 15 | SI | 47 | / | 79 | O | 111 | o |
| 16 | DLE | 48 | 0 | 80 | P | 112 | p |
| 17 | DC1 | 49 | 1 | 81 | Q | 113 | q |
| 18 | DC2 | 50 | 2 | 82 | R | 114 | r |
| 19 | DC3 | 51 | 3 | 83 | S | 115 | s |
| 20 | DC4 | 52 | 4 | 84 | T | 116 | t |
| 21 | NAK | 53 | 5 | 85 | U | 117 | u |
| 22 | SYN | 54 | 6 | 86 | V | 118 | v |
| 23 | ETB | 55 | 7 | 87 | W | 119 | w |
| 24 | CAN | 56 | 8 | 88 | X | 120 | x |
| 25 | EM | 57 | 9 | 89 | Y | 121 | y |
| 26 | SUB | 58 | : | 90 | Z | 122 | z |
| 27 | ESC | 59 | ; | 91 | [ | 123 | { |
| 28 | FS | 60 | \< | 92 | \ | 124 | | |
| 29 | GS | 61 | = | 93 | ] | 125 | } |
| 30 | RS | 62 | \> | 94 | ^ | 126 | ~ |
| 31 | US | 63 | ? | 95 | \_ | 127 | DEL |

## Appendix 2 - Differences and Applications List, Tuple, Set and Dictionary in Python

**Lists** are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.

**Tuple** A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.

**Set** A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set.

**Dictionary** in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.

List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the data in an efficient manner.



| List                                                                                                          | Tuple                                                                                               | Set                                                                                 | Dictionary                                                                       |
|---------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| List is a non-homogeneous data structure that stores the elements in single row and multiple rows and columns | Tuple is also a non-homogeneous data structure that stores single row and multiple rows and columns | Set data structure is also non-homogeneous data structure but stores in single row  | Dictionary is also a non-homogeneous data structure which stores key value pairs |
| List can be represented by [ ]                                                                                | Tuple can be represented by ()                                                                      | Set can be represented by { }                                                       | Dictionary  can be represented by { }                                            |
| List allows duplicate elements                                                                                | Tuple can use nested among all                                                                      | Set can use nested among all                                                        | Dictionary can use nested among all                                              |
| Example: [1, 2, 3, 4, 5]                                                                                      | Example: (1, 2, 3, 4, 5)                                                                            | Example: {1, 2, 3, 4, 5}                                                            | Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}                                                         |
| List can be created using `list()` function                                                                   | Tuple can be created using `tuple()` function.                                                      | Set can be created using `set()` function                                           | Dictionary can be created using `dict()` function.                               |
| List is mutable i.e we can make any changes in list.                                                          | Tuple is immutable i.e we can not make any changes in tuple                                         | Set is mutable i.e we can make any changes in set. But elements are not duplicated. | Dictionary is mutable. But Keys are not duplicated.                              |
| List is ordered                                                                                               | Tuple is ordered                                                                                    | Set is unordered                                                                    | Dictionary is ordered (Python 3.7 and above)                                     |
| Creating an empty list `l = []`                                                                               | Creating an empty Tuple `t = ()`                                                                    | Creating a set `a = set(); b = set(a)`                                              | Creating an empty dictionary `d = {}`                                            |

Below is the program for implemetnation of list, tuple, set and dictionary.

<iframe src="https://trinket.io/embed/python3/491774e3d7" width="100%" height="356" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

