Arrays and lists in Python — the basics
In this lesson you will learn how to use lists in Python, how to keep several values and how to process them with loops. Lists are the basic data type for working with collections and they are key to many algorithms.
In Python the term list is used for keeping several values in one variable in a structured way. A list is a dynamic collection of elements that are ordered and changeable — this means you can access them through an index and easily add, remove or change elements.
A Python list can contain elements of different types: numbers, text, boolean values, and even other lists ⟶ e.g. [1, "Ana", True, [2, 3]].
This is one of the main advantages of lists — flexibility in keeping different types of data.
On the other hand, when we talk about arrays, we usually mean a data structure that contains elements of the same type — most often using a module such as array or the popular library NumPy.
In such arrays all elements must be of the same type, which allows more efficient use of memory and faster mathematical operations.
In short, the key differences are:
- Data types: lists can contain elements of different types, while arrays usually require all elements to be of the same type.
- Module and declaration: lists are part of the language and need no additional libraries, while arrays are usually created with modules such as
arrayorNumPy. - Purpose: lists are very flexible and suitable for general use, while arrays are more often used in numerical and performance-demanding applications.
After this introduction we turn to practical examples and operations on lists, such as accessing elements, iteration, adding and removing elements.
1. Creating a list
A list is defined by putting elements in square brackets:
numbers = [1, 2, 3, 4, 5]
names = ["Ana", "Marko", "Jovana"]
empty_list = []
2. Accessing elements
The elements of a list are accessed with an index (it starts from 0):
print(numbers[0]) # prints 1
print(names[2]) # prints "Jovana"
3. Iterating through a list
With a for loop we can go through all the elements:
for number in numbers:
print(number)
4. Adding and removing elements
We can add elements to a list or remove them:
numbers.append(6) # adds 6 to the end of the list
numbers.remove(3) # removes the value 3
last = numbers.pop() # removes and returns the last element
5. Additional operations
- The length of a list:
len(numbers) - Sorting:
numbers.sort() - Checking membership:
if 4 in numbers:
6. Mini tasks
- Make a list of your favourite fruits and print them
- Print all the elements of a list of numbers that are greater than 10
- Count how many times a certain number appears in the list
- Make a list of the squares of the numbers from 1 to 10
When you master lists, you will be able to combine loops and collections, which is the basis for all more complex projects and algorithms.
Practice tasks: working with lists in Python
The following tasks are for practising work with lists, loops and basic algorithmic thinking. The tasks are easy and medium difficulty and often appear in practice and school examples.
Task 1: Counting the elements greater than the average
Task:
A list of numbers is given. Calculate the average value of the elements of the list and
count how many elements are greater than that average.
Algorithm
- Calculate the sum of the elements of the list
- Find the average
- Go through the list again and count the elements greater than the average
Solution
numbers = [4, 7, 2, 9, 5, 10]
total = sum(numbers)
average = total / len(numbers)
counter = 0
for x in numbers:
if x > average:
counter += 1
print("Average:", average)
print("Number of elements greater than the average:", counter)
Average: 6.166666666666667
Number of elements greater than the average: 3
Additional explanation:
The task uses two passes through the list (one hidden inside sum),
which is often acceptable for problems like this.
Task 2: Reversing the order of the elements
Task:
Write a program that creates a new list with the elements in reverse order.
Do not use the built-in function reverse().
Algorithm
- Create an empty list
- Go through the original list backwards
- Add the elements to the new list
Solution
items = [1, 2, 3, 4, 5]
reversed_list = []
for i in range(len(items) - 1, -1, -1):
reversed_list.append(items[i])
print(reversed_list)
[5, 4, 3, 2, 1]
Comment:
Although Python has simpler solutions, this task develops an understanding
of indexes and working with loops.
Task 3: Extracting the unique elements
Task:
From the given list extract the elements that appear only once.
Algorithm
- For every element check how many times it appears
- If it appears exactly once, add it to the new list
Solution
items = [1, 2, 2, 3, 4, 4, 5]
unique = []
for x in items:
if items.count(x) == 1:
unique.append(x)
print(unique)
[1, 3, 5]
Additional explanation:
The method count() is simple, but it can be slow for very large lists.
In more advanced examples a dictionary is used.
Task 4: Checking whether a list is sorted
Task:
Check whether the elements of a list are sorted in ascending order.
Algorithm
- Compare every element with the next one
- If one is greater than the next — the list is not sorted
Solution
items = [1, 3, 5, 7, 9]
is_sorted = True
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
is_sorted = False
break
print("The list is sorted:", is_sorted)
Additional explanation:
This approach is efficient because it stops as soon as a mistake is found.
Task 5: Rotating a list to the left
Task:
Rotate a list to the left by one place.
Example: [1, 2, 3, 4] → [2, 3, 4, 1]
Algorithm
- Save the first element
- Move the other elements to the left
- Put the first element at the end
Solution
items = [1, 2, 3, 4]
first = items[0]
for i in range(len(items) - 1):
items[i] = items[i + 1]
items[-1] = first
print(items)
[2, 3, 4, 1]
Additional comment:
Rotations are common in algorithms and data structures,
and this task develops thinking about moving elements.
Lists in Python and the idea of "arrays"
In programming languages such as C, C++ or Java the term array is often used for a collection of elements of the same type and a size defined in advance. However, Python has no classic array in that sense.
In Python the data structure most often used is called a list. Lists are sometimes informally called "arrays", but that is not completely precise, because Python lists behave much more flexibly than classic arrays in other languages.
The main differences between Python lists and classic arrays:
- Python lists are dynamic – their size can change while the program runs.
- A list can contain elements of different data types.
- There is no fixed memory reserved in advance as with static arrays.
- Lists are mutable, which means that their elements can be changed.
The following example shows that a Python list can contain different types of data, which is not allowed in classic arrays:
items = [10, 3.14, "Python", True]
print(items)
Because of all this, in Python it is more correct to use the term list, while the word "array" can be used only as a simplified explanation for beginners.
If a structure more similar to a classic array is needed (with elements of the same type
and greater efficiency), Python offers additional modules, such as
array or the NumPy library.
Indexing and slices in Python lists
Every element in a Python list has its own index. Indexes start from 0, which means that the first element of the list has the index 0, the second the index 1, etc.
names = ["Ana", "Marko", "Jovana", "Nikola"]
print(names[0]) # Ana
print(names[2]) # Jovana
Python also allows negative indexes.
The index -1 means the last element of the list,
-2 the one before last, etc.
print(names[-1]) # Nikola
print(names[-2]) # Jovana
Besides accessing single elements, Python lets you extract
a slice of a list with the so-called slice syntax:
items[start:end].
The element with the index start is included, while the element with
the index end is not included in the slice.
numbers = [0, 1, 2, 3, 4, 5, 6]
print(numbers[1:4]) # [1, 2, 3]
print(numbers[:3]) # [0, 1, 2]
print(numbers[3:]) # [3, 4, 5, 6]
Slicing can also be used with a step, which lets you skip elements.
print(numbers[::2]) # [0, 2, 4, 6]
print(numbers[::-1]) # [6, 5, 4, 3, 2, 1, 0]
It is especially important to point out that slicing a list returns a new list and does not change the original list.
More advanced list methods and list comprehensions
Besides the basic operations, Python lists support many more advanced methods that make working with data efficient and readable. These methods often replace longer loops and simplify the code.
The most commonly used list methods
append(x)– adds an element to the end of the listextend(iterable)– adds several elements from another collectioninsert(i, x)– inserts an element at the given positionremove(x)– removes the first occurrence of an elementpop(i)– removes and returns the element at positioniindex(x)– returns the index of the first occurrence of an elementcount(x)– counts the occurrences of an elementsort()– sorts the list (changes the original list)reverse()– reverses the order of the elements
numbers = [5, 2, 9, 1, 5]
numbers.append(7)
numbers.insert(1, 10)
numbers.remove(5)
print(numbers)
[10, 2, 9, 1, 5, 7]
It is important to note that the methods sort() and reverse() change the original list. If the original order needs to be kept,
the function sorted() can be used.
original = [3, 1, 4, 2]
sorted_list = sorted(original)
print(original) # [3, 1, 4, 2]
print(sorted_list) # [1, 2, 3, 4]
List comprehensions
List comprehensions are Python's
short and elegant way of creating lists from existing
collections. They most often replace for loops with additional conditions.
The general form of a list comprehension is:
new_list = [expression for element in collection]
Example: making a list of the squares of numbers.
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)
List comprehensions can also contain a condition.
even = [x for x in numbers if x % 2 == 0]
print(even)
Compared with a classic for loop, list comprehensions
produce shorter, more readable and often more efficient code.
Still, for more complex logic standard loops are recommended for better readability.
Mutability and references of Python lists
Python lists are mutable data structures, which means that their elements can be changed even after the list has been created. It is very important to understand this behaviour, because it can lead to unexpected results when working with several variables.
When a list is assigned to another variable, no new list is made; both variables refer to the same list in memory.
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1)
print(list2)
Although you might expect the change to apply only to list2,
both variables show the same result:
[1, 2, 3, 4]
[1, 2, 3, 4]
The reason is that list1 and list2 refer to
the same object in memory.
Copying a list
If a real copy of a list is needed, its content must be copied explicitly.
An example using the method copy():
list1 = [1, 2, 3]
list2 = list1.copy()
list2.append(4)
print(list1) # [1, 2, 3]
print(list2) # [1, 2, 3, 4]
Alternatively, a copy of a list can also be made with slicing:
list2 = list1[:]
In both cases list1 and list2 are independent lists,
so changes in one do not affect the other.
Understanding mutability and references is key to using Python lists correctly and preventing logical errors in programs.
When to use lists, and when other Python collections
Python offers several built-in data structures for working with collections. Although lists are used very often, it is important to know when they are the right choice, and when it is better to use another structure.
Lists (list)
Lists are ordered, mutable collections that can contain elements of different types. They are used when you need to:
- change the content of a collection (adding, deleting, changing elements),
- keep the order of the elements,
- access elements through an index.
numbers = [1, 2, 3]
numbers.append(4)
Tuple (tuple)
A tuple is similar to a list, but it is immutable. Once created, a tuple cannot be changed.
A tuple is used when the data should not change, for example:
- the coordinates of a point,
- constant values,
- the return values of functions.
point = (10, 20)
# point[0] = 5 # Error – a tuple is immutable
Set (set)
A set is an unordered collection of unique elements. It does not allow duplicates and does not use indexes.
A set is useful when you need to:
- remove duplicates from a collection,
- check quickly whether an element exists,
- do set operations (union, intersection, difference).
numbers = [1, 2, 2, 3, 3]
unique = set(numbers)
print(unique)
Dictionary (dict)
A dictionary keeps data in the form of key–value pairs. It is used when it is important to find a value quickly by some key.
student = {
"name": "Ana",
"age": 20,
"average": 9.5
}
print(student["name"])
A short comparison
- List – when you need order and changing elements
- Tuple – when the data should not change
- Set – when unique elements are important
- Dict – when data is connected through keys
The right choice of data structure makes the code more readable, more efficient and less prone to errors.
Mini quiz — Python lists and collections
Click to check whether you understand how lists, indexing, slices, mutability and the differences between lists and other Python collections work.
Open the quiz
Mini quiz: Lists in Python
1. What will be printed?
items = [10, 20, 30, 40]
print(items[-1])
2. What is the result of the following slice?
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[2:5])
3. What will happen in the following example?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
4. What does the following list comprehension do?
result = [x for x in range(10) if x % 2 == 0]
5. Which structure is the MOST SUITABLE if you want to remove duplicates from a list?
Tasks for independent work – Python lists
The following tasks are meant for checking your understanding of Python lists. The tasks are divided by difficulty and are suitable for students in grades 7 and 8, as well as for the basic competition level.
Basic tasks
-
Write a program that creates a list of integers and prints:
- the first element of the list,
- the last element of the list,
- the number of elements in the list.
-
A list of names is given.
Print all the names one below the other using a
forloop. - A list of numbers is given. Calculate and print the sum of all the elements of the list.
Medium tasks
- A list of numbers is given. Make a new list that contains only the even numbers from the original list.
- Write a program that checks whether a given number is in the list. If it is, print its index.
- A list of numbers is given. Create a new list that contains the squares of all the elements. (The task can also be solved with a list comprehension.)
Harder tasks (competition level)
-
A list of integers is given.
Find the longest increasing run of consecutive elements in the list.
Hint: use variables that remember the current length of the run and the maximum length so far. -
A list of numbers is given.
Check whether the list is a palindrome
(the list is the same when read from left to right and from right to left).
Hint: compare the original list with its reversed version. -
A list of numbers is given.
Form a new list so that every element is
the difference between neighbouring elements
of the original list.
Hint: use indexes and watch the boundaries of the list.
Tip: Before you start writing code, think: is it necessary to change the list, to make a new list, or to use additional variables?
