Python for AI 103 Warm-up

Acknowledgement: This post is based mainly on TAs Thai Nguyen and Dang Nha’s presentation and slides and partly on on TA, STA, and peers’ responses from the course AIO2025 offered by AI VIETNAM.

Relevance: The audience of this lecture were those who have read Python for AI 102, had some coding experience, and known a bit of AI knowledge. Absolute beginners are encouraged to read the material and repeatedly practice coding without AI assistance to strengthen their coding and code-reading skills. Note that only necessary Python knowledge is introduced here.

In today’s post, we’ll explore the basics of lists.


List

list_name = [element_1, ..., element_n]

Imagine a train has many wagons. If they are not connected, the train cannot run. But connecting them in an orderly fashion puts it to work. A data structure, in an analogous sense, is an efficient way of organizing and storing data in a computer system. A list is a built-in data structure. We can use it to construct user-defined data structures.

You can think of a list as an organized shopping cart that can carry literally anything. Formally, a list is a container consisting of multiple elements:

  • It can be empty: a_list = [] is an empty list.
  • Elements are ordered: positions of elements stay unchanged after creation unless they are updated.
  • Elements are indexable: elements are associated with indices, starting from 0 at the left end.
  • Elements are heterogeneous: a_list = [True, 7, "AIVIETNAM", 8.7, 7] is accepted.
  • Elements can be duplicated: different elements can have the same value.
a_list = [1, 2, 3]
for item in a_list:
    print(f'value = {item}, ID = {id(item)}')

print(f'ID of a_list = {id(a_list)}')

'''
value = 1, ID = 140719557454264
value = 2, ID = 140719557454296
value = 3, ID = 140719557454328
ID of a_list = 1879354544512
'''

We can see from this example that elements of a list are discretely stored and the address of the list is entirely different.

Indexing and Slicing

The associated number mentioned above is called an index. We can use an index to query and modify the value of one element. There are two types:

  • Forward index: starts at $0$ and increases by $1$ from left to right.
  • Backward index: starts at $-1$ and decreases by $1$ from right to left.
a_list = [5, 6, 7, 8]
a_list[2]
>>> 7

a_list[-1]
>>> 8

Similarly, we can access the values of several continuous elements by a technique called slicing, a_list[start:end:step]. This results in a sublist

  • beginning at start with $0$ by default
  • increasing by step with $1$ by default
  • ending before reaching end with the number of elements by default.
a_list = [5, 6, 7, 8]

# test
a_list[1:6:1]
>>> [6, 7, 8]

a_list[::2]
>>> [5, 7]

a_list[6:2:-1]
>>> [8]

a_list[-2:-4]
>>> []

a_list[1:-2]
>>> [6]

Elements of a sublist (after slicing) have the same addresses as in the original list. But changing an element’s value in the sublist does not affect the original and vice versa.

$+$ and $*$ Operators

The $+$ operator is to concatenate two lists while the $*$ operator concatenates multiple copies of a given list.

data1 = [6, 5, 7]
data2 = [1, 9, 2]

# test
data1 + data2
>>> [6, 5, 7, 1, 9, 2]

data = [6, 5]

# test
data * 3
>>> [6, 5, 6, 5, 6, 5]

List Methods

list_name.method_name(argument_if_required)

Besides accessing data, we want to manipulate it as well. Built-in methods allow us to do so. We’ll use a_list = [4, 5, 6, 7, 4, 7] for examples below.

Methods Purposes Examples
append() Add only one given value to the end a_list.append(10)
a_list
>>> [4, 5, 6, 7, 4, 7, 10]
insert() Add only one given value to the position of a given index a_list.insert(2,10)
a_list
>>> [4, 5, 10, 6, 7, 4, 7]
extend() Add elements of a given list to the original a_list.extend([10, 8])
a_list
>>> [4, 5, 6, 7, 4, 7, 10, 8]
pop() Delete the last element by default or delete by index a_list.pop(1)
>>> 5
a_list
>>> [4, 6, 7, 4, 7]
remove() Delete the first occurence of a given value a_list.remove(7)
a_list
>>> [4, 5, 6, 4, 7]
del Delete a given list of elements del a_list[1:4]
a_list
>>> [4, 7, 7]
clear() Delete all elements a_list.clear()
a_list
>>> []
index() Return the index of the first occurence of a given value a_list.index(7) >>> 3
a_list
>>> [4, 5, 6, 7, 4, 7]
reverse() Reverse elements a_list.reverse()
a_list
>>> [7, 4, 7, 6, 5, 4]
sort() Arrange elements in an increasing order by default a_list.sort()
a_list
>>> [4, 4, 5, 6, 7, 7]
count() Return the number of a given value a_list.count(7)
>>> 2
a_list
>>> [4, 5, 6, 7, 4, 7]
copy() Return the deep copy of a list a_list.copy()
>>> [4, 5, 6, 7, 4, 7]
a_list
>>> [4, 5, 6, 7, 4, 7]


  • The append() method returns None since the only action it does is adding an element to a list.
  • The same goes for the remove() method since it just deletes an element.
  • However, the pop() method is to grab and throw the given value somewhere then delete it. If you want to keep that value, you can catch and carry it in a variable basket.
  • We can sort() a list in the reverse order by make reverse = True as its argument.
  • Assigning a list to the original list makes a copy cat—update in one affects the other. To avoid such a situation, we have the copy() method which only has the same look but is different on the inside.
Practice Exercises
Exercise 1: Write a function that removes all elements of the same value given that value.
Exercise 2: What is the output of the following? Explain your answer.

a = [1, 2, 3]
b = a
b.append(4)
print(a)


a = [1, 2]
b = [3, 4]
print(a + b)


a = [1]
b = a * 3
b[0] = 0
print(a)
print(b)


a = [10, 20, 20, 30, 40, 50]
a.remove(20)
a.pop(2)
print(a)


a = [1, 2, 3, 4, 5]
print(a[-1:-3])


List Built-in Functions

Functions Purposes Examples
len() Return the number of elements len(a_list)
>>> 6
min() Return the minimum element min(a_list)
>>> 4
max() Return the maximum element max(a_list)
>>> 7
sorted(iterable) Arrange elements in an ascending order by default a_sorted_list = sorted(a_list)
a_sorted_list
>>> [4, 4, 5, 6, 7, 7]
sum(iterable, start) Return the sum of start and all elements sum(a_list, 7)
>>> 40
reversed(iterable) Reverse elements  
enumerate(iterable) Return a sequence of index and value pairs  
zip(*iterators) Return a sequence of value pairs with matching index  


  • start is optional in the sum() function. It then returns the sum of all elements.
  • The enumerate() function can also have start as the starting index.
  • Using *iterators can save memory, avoiding memory overflow.
  • Similar to the sort() method, we can sorted() a list in the reverse order by make reverse = True as its argument.
data1 = [6, 5, 7]
data2 = [1, 9, 2]

for index, value in enumerate(data1):
    print(f'enumerate: index = {index}, value = {value}')

for v1, v2 in zip(data1, data2):
    print(f'zip: v1 = {v1}, v2 = {v2}')

'''
enumerate: index = 0, value = 6
enumerate: index = 1, value = 5
enumerate: index = 2, value = 7
zip: v1 = 6, v2 = 1
zip: v1 = 5, v2 = 9
zip: v1 = 7, v2 = 2
'''

Practice and Exercises

Two Sum
Problem statement: Given an list of integers *data* and an integer *target*, write a function that returns indices of two numbers whose sum equals *target*.
Breakdown:
  • data = [6, 5, 7, 1, 7, 9, 2].
  • target = 8.
  • the function returns 2, 3 and 0, 5.
  • $\text{complement} = \text{target} - \text{value}$ where value is an element in data.
Idea: We'll here use dictionary which is introduced in Python for AI 104. We'll utilize the property that a dictionary can hold two values in one item to store and access a list's elements and their indices whenever we need.
  1. Start with an empty dictionary. This dictionary will be added with the list's elements and their indices one by one.
  2. Create an empty list that will store the desired index pairs.
  3. Instead of checking the sum of every possible pair in a loop, take each element's complement and check if it is in the dictionary at the current step.
    • If it is, we've found one desired index pair and update it to the list.
    • If not, we can move on to the next element.
    • We add the element and its index as a key and value of the dictionary, respectively.
Practice Exercises
Exercise 1: Wrtie a function that calculates the sum of even numbers in a list using while and for loops and some list basics.
Exercise 2: Wrtie a function for the two sum problem using only list.
Exercise 3: Implement the function described in the two sum problem above.
Exercise 4: Which function for the two sum problem is less time-consuming? Explain why.
Exercise 5: What if the same number appears next two each other? Modify the code if needed.
Exercise 6: What is the output of the following?

a = [1, 2]
b = ['a', 'b, 'c']
print(list(zip(a, b)))


a = [1, [2, 3], [2, 3], 4, 5]
print(a.count([2, 3]))
print([-2: 1: -2])


:speech_balloon: FAQ

Here are some good questions asked during class. The answers to these questions came from either some admin, TA, STA, or members of AIO2025.

Questions Answers
What is the difference between a list and an array? A list can contain elements of different types while an array can only contain elements of a single type.
How do indices in a nested list work? Take an inner list with its index from the outter list, then take its elements with their indices of the inner list. For example, a_list[2][1] is the second element of the third inner list.
How do the memory addresses of elements in a list work? Technically, each list contains random pointers which point/hold values. That’s why the memory addresses are not continuous.
Can I use slicing to access elements at discrete positions? For example, the wanted indices are 1, 4, and 5. No. Slicing only works for equally-spaced positions.
Are append() and extend() the same? No. append() adds only one value while extend() adds at least one value under list format.
If the same number appears more than one time, can I remove one with a specific index? Yes. You need to write your own function to do so.
When do I use zip()? You can use it to pair train-test datasets.
What is *kwargs? It’s keyword arguments. Arguments are key-value pairs.
What is *iterators? In general, it is *arg, which means you can have multiple arguments.
Resources https://colab.research.google.com/drive/1katWdH8FxP4bgT1z8TgfSfNtuF7SfhKz?usp=sharing&pli=1#scrollTo=mvFyDSWZh1_d





    Enjoy Reading This Article?

    Here are some more articles you might like to read next:

  • Python for AI 103
  • Python for AI 104
  • Python for AI 101
  • Math for AI 101
  • Math for AI 101 Warm-up