- What is a Python list?
- Accessing items in a list
- Change the value of a list item
- Length of a Python list
- Iterate through items in a Python list
- Add or remove items from the list
- List in comprehension
- List slicing
- Main methods associated with a python list
- Summary of characteristics and operations related to Python lists
1. What is a Python list?
In Python, a list is a built-in data structure that allows you to store and manipulate a collection of items. It is an ordered sequence of elements enclosed in square brackets [ ] and separated by commas. Lists are versatile and can contain elements of different data types, such as integers, floats, strings, or even other lists.
In Python, lists are written in brackets:
1 |
List = [ ...] |
Example
1 2 3 4 |
#Creating a list myList = ["Python", "Django", "Laravel"] # Displaying the list print(myList) # output: ['Python', 'Django', 'Laravel'] |
2. Access the elements of a list.
To access an element of a list, simply enter the name of the list followed by the index of the element concerned in square brackets:
Example
1 2 3 |
Print the 2nd element of the list: myList = ["Python", "Java", "PHP"] print(myList[1]) # output 'Java' |
3. Modify the value of an item in the list
To change the value of a specific element, refer to the index number:
Example (Change the 3rd element of the list)
1 2 3 |
myList = ["Python", "Java", "PHP"] myList[2]="NodeJS" print(myList) #output: ['Python','Java','NodeJS'] |
4. Length of a Python list
To determine the number of elements in a list (or length of the list), we use the len() method:
Example
1 2 3 4 |
#Display the number of elements in the list: myList = ["Python", "Django", "PyGame"] print("The length of the list is",len(myList)) #output: The length of the list is 3 |
5. Iterate through the elements of a Python list
The Python language has the for structure which allows you to browse any iterable (list, character string, etc.)
Example
1 2 3 4 |
#Print all elements of the list, one by one: myList = ["Python", "Java", "NodeJS"] for element in myList: print(element) # Print all list elements one by one. |
You can also iterate through the elements of the list using indexes
Example
1 2 3 4 5 6 |
#Print all elements of the list, one by one: myList = ["Javascript", "PHP", "NodeJS"] # getting the length of list n = len(myList) for i in range(0, n): print(myList[i]) # Print all list items one by one. |
6. Add or remove items from the list
6.1 Add an item to a Python list
To add an item to the end of a python list, just use the append() method:
Example
1 2 3 4 |
#add an element at the end of the list with the append() method: myList = ["Python", "Java", "PHP"] myList.append("Django") print(myList) #output: ["Python", "Java", "PHP", "Django"] |
To add an item at a specified index, just use the insert() method:
Example
1 2 3 4 |
#Insert an element in second position: myList = ["Python", "Java", "PHP"] myList. insert(1, "PyGame") print(myList) # output: ["Python", "PyGame", "Java", "PHP"] |
6.2 Remove an item from a Python list
There are several methods to remove items from a list:
- remove(): removes a specified element.
- pop(): delete an element by specifying its index (or the last element if no index is specified)
- del: keyword deletes the element at the specified index ( del also completely deletes the list)
- clear(): empty the list
Example
1 2 3 4 |
#remove a specified element with the remove() method myList = ["Python", "C++", "PHP"] myList.remove("PHP") print(myList) #output: ["Python", "C++"] |
Example
1 2 3 4 |
#Remove specified index item with pop() method myList = ["Python", "Java", "PHP"] myList.pop(1) print(myList) #Displays: ["Python", "PHP"] |
Example
1 2 3 4 |
#delete element at a specified index with the del method: myList = ["Python", "Java", "PHP"] del myList[2] print(myList) #Displays: ["Python", "Java"] |
The del keyword can also completely delete the list:
Example
1 2 3 |
myList = ["Python", "Django", "PyGame"] del myList print(myList) #this will cause an error because "myList" no longer exists. |
Example (clear the list)
1 2 3 |
myList = ["Python", "Django", "Flask"] myList. clear() print(myList) #this an empty list: [] |
7. List comprehension
The list comprehension is an elegant and concise way to create a new list from an existing list in Python.
A list comprehension consists of an expression followed by a for statement in square brackets.
Here is an example of creating a list in formed comprehension of even numbers
Example
1 2 3 |
list_even = [2*n for n in range(5)] print("List of even numbers: ", list_even) # displays: List of even numbers: [0, 2, 4, 6, 8] |
You can also add a condition to the for loop, for example if you want to get the list of even numbers that are multiple of 3:
Example
1 2 3 |
list_even_mult_3 = [2*n for n in range(20) if n%3 == 0] print("even numbers multiple of 3: ", list_even_mult_3) # displays: even numbers multiple of 3: [0, 6, 12, 18, 24, 30, 36] |
8. List slicing
We can perform a slicing to a range of items in a list using the slicing operator:
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# List slicing in Python my_list = ['h','e','l','l','o','w','o','r','l', 'd'] # split from index 3 to index 6 print(my_list[3:6]) # prints: ['l', 'o', 'w'] # slicing from index 4 to end print(my_list[4:]) # prints: ['o', 'w', 'o', 'r', 'l', 'd'] # slicing from start up to index 5 not included print(my_list[:5]) # prints: ['h','e','l','l','o'] # slicing from start to end print(my_list[:])# prints: ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd' ] # extract the last element print(my_list[-1])# displays: [d] # extract element with index 4 counting from last element print(my_list[-4]) # prints: o |
9. Main methods associated with a python list
Python has a set of built-in methods for performing operations on lists:
- append(): Adds an item to the end of the list
- clear(): Remove all items from the list
- copy(): Returns a copy of the list
- count(): Returns the number of elements with the specified value
- extend(): Adds the elements of a list (or any iterable element) to the end of the current list
- index(): Returns the index of the first element with the specified value.
- insert(): Adds an element at the specified position
- pop(): Deletes the element at the specified position
- remove(): Removes the element with the specified value
- reverse(): Reverse the order of the list
- sort(): Sorts the list
10. Summary of characteristics and operations related to Python lists
Here's a description of some key characteristics and operations related to Python lists:
- Mutable: Lists are mutable, meaning you can modify their elements. You can change, add, or remove items from a list after it is created.
- Ordered: Lists maintain the order of the elements as they are inserted. The first element is at index 0, the second at index 1, and so on. You can access elements in a list by their index.
- Dynamic Size: Lists in Python can grow or shrink dynamically. You can add or remove items without needing to specify a fixed size in advance.
- Heterogeneous Elements: Lists can contain elements of different data types. For example, a single list can hold integers, strings, and floats together.
- Indexing and Slicing: You can access individual elements in a list using square brackets and the index of the item you want to retrieve. Negative indexing is also supported, allowing you to access elements from the end of the list. Additionally, you can use slicing to extract sublists by specifying start and end indices.
- Common Operations:
- Append: Adds an item to the end of the list using the append() method.
- Insert: Inserts an item at a specified position in the list using the insert() method.
- Remove: Removes the first occurrence of a specified item from the list using the remove() method.
- Length: Retrieves the number of items in the list using the len() function.
- Sort: Sorts the elements of the list in ascending order using the sort() method.
- Concatenate: Combines two lists together using the + operator.
- Iterate: You can iterate over the elements of a list using loops or list comprehensions.
Younes Derfoufi
CRMEF OUJDA