Lists in Python
In this article, we will explain lists in Python.
You can learn various operations on lists and list comprehensions with code samples.
YouTube Video
Lists in Python
In Python, the data structure commonly referred to as an array is usually implemented as a 'list.'. Python lists are very flexible and allow the following operations:.
Creating a list
1# Create an empty list
2my_list = []
3print(my_list)
4
5# Create a list with elements
6my_list = [1, 2, 3, 4, 5]
7print(my_list)
- You can create a list as empty or with initial elements specified.
Accessing and Modifying List Elements
1my_list = [1, 2, 3, 4, 5]
2print(my_list) # [1, 2, 3, 4, 5]
3
4element = my_list[0] # Get the element at index 0
5print(element) # 1
6
7my_list[1] = 10 # Change the element at index 1 to 10
8print(my_list) # [1, 10, 3, 4, 5]
- List elements can be accessed or modified by specifying their index.
Getting the Length of a List
1my_list = [1, 2, 3, 4, 5]
2
3length = len(my_list)
4print(my_list)
5print(length)
- Using the
len()
function, you can get the number of elements.
Adding and inserting elements into a list
1my_list = [1, 2, 3, 4, 5]
2
3my_list.append(6)
4print(my_list)
- Using the
append()
method, you can add an element to the end of a list.
1my_list = [1, 2, 3, 4, 5]
2
3my_list.insert(2, "A") # Insert "A" at index 2
4print(my_list)
- Using the
insert()
method, you can insert an element at any position.
Removing elements from a list
1my_list = [1, 2, 3, 4, 5]
2
3del my_list[2] # Delete the element at index 2
4print(my_list)
5
6removed_element = my_list.pop(0) # Delete and return the element at index 0
7print(removed_element)
8print(my_list)
- Using either the
del
statement or thepop()
method, you can remove an element at a specified position. Thepop()
method returns the removed element.
1my_list = [1, 2, 3, 4, 5]
2
3my_list.remove(5) # Remove the first occurrence of 5 from the list
4print(my_list)
- Using the
remove()
method, you can delete the first occurrence of a specified value.
List Slicing
1my_list = [1, 2, 3, 4, 5]
2
3print(my_list[1:3]) # [2, 3]
4print(my_list[:3]) # [1, 2, 3]
5print(my_list[2:]) # [3, 4, 5]
6print(my_list[:]) # [1, 2, 3, 4, 5]
- The slicing syntax
[start:end]
gets elements fromstart
toend - 1
. You can also omit eitherstart
orend
.
Sorting a list
1my_list = [2, 1, 5, 4, 3]
2print(my_list) # [2, 1, 5, 4, 3]
3
4my_list.sort() # Sort in ascending order (modifies the list)
5print(my_list) # [1, 2, 3, 4, 5]
6
7my_list.sort(reverse=True) # Sort in descending order
8print(my_list) # [5, 4, 3, 2, 1]
- The
sort()
method can sort a list in ascending or descending order.
1my_list = [3, 1, 4, 2]
2sorted_list = sorted(my_list)
3print(my_list) # [3, 1, 4, 2]
4print(sorted_list) # [1, 2, 3, 4]
- The
sorted()
function allows you to create a new sorted list without modifying the original list.
Creating a reversed list
1my_list = [1, 2, 3, 4, 5]
2
3my_list.reverse()
4print(my_list)
- The
reverse()
method can reverse the order of elements in a list.
List Comprehension
In Python, you can use the powerful list comprehension syntax to generate lists concisely. List comprehensions allow you to write in a single line the process of generating new lists using for-loops. You can also use conditions to extract only specific elements.
1# Generate squares of numbers from 0 to 9
2squares = [x**2 for x in range(10)]
3print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4
5# Use a condition to extract squares of even numbers only
6even_squares = [x**2 for x in range(10) if x % 2 == 0]
7print(even_squares) # [0, 4, 16, 36, 64]
8
9# Store either the square or the original number based on a condition
10squares_or_original = [x**2 if x % 2 == 0 else x for x in range(10)]
11print(squares_or_original)
12# Output: [0, 1, 4, 3, 16, 5, 36, 7, 64, 9]
- With list comprehensions, you can concisely create new lists using loops and conditions. By using
if
andif-else
, you can create list comprehensions that extract elements or generate different values based on conditions.
Concatenation of lists
1# Concatenate two lists using the + operator
2a = [1, 2, 3]
3b = [4, 5, 6]
4combined = a + b
5print(combined) # [1, 2, 3, 4, 5, 6]
6
7# Extend an existing list with another list
8a = [1, 2, 3]
9b = [4, 5, 6]
10a.extend(b)
11print(a) # [1, 2, 3, 4, 5, 6]
12
13# Concatenate multiple lists using unpacking (*)
14a = [1, 2, 3]
15b = [4, 5, 6]
16c = [7, 8, 9]
17merged = [*a, *b, *c]
18print(merged) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
- In Python, you can concatenate lists using the
+
operator, theextend()
method, or unpacking syntax (*
). It is common to use+
or*
when creating a new list, andextend()
when updating an existing list.
Summary
Lists are a fundamental data structure in Python and are used in many situations. There are many flexible and useful features, and mastering them makes programming more efficient.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.