Python stands out as a versatile and beginner-friendly language, gaining immense popularity due to its simplicity, readability, and extensive range of applications. Lists are one of its built-in data structures. In this blog, we will learn about Python lists and its methods.
Let’s start!
What is a List?
In Python, a list is an ordered collection of data items. In a list, you can store multiple items of different data types, including numbers, strings and even other lists. List items are separated by commas and enclosed within square brackets []
.
Example: 1
A list containing numbers.
list1 = [11,2,13,9,15]
print(list1) #Output: [11,2,13,9,15]
Example: 2
A list containing strings.
list2 = ["Apple", "Banana", "Orange"]
print(list2) #Output: ['Apple', 'Banana', 'Orange']
Example: 3
A list containing different data types.
list3 = [1, "John",10, 5.3]
print(list3) #Output: [1, 'John', 10, 5.3]
Example: 4
A list containing another list.
list4 = [1, 2, [3, 4.2]]
print(list4) #Output: [1, 2, [3, 4.2]]
Lists are mutable which means you can change them after creation.
Creating Lists
You can create lists in the following ways.
- List literals
- Using the
list()
constructor - List comprehension
List literals
You can create lists by defining the list items within square brackets []
, separated by commas.
For example:
numbers = [11,2,13,9,15]
print(numbers) #Output: [11,2,13,9,15]
Using the list()
constructor
You can create a list using the list()
constructor, which converts other iterable objects like strings, other lists, tuples, dictionaries or sets into lists.
For example:
list1 = list("Apple")
print(list1) #Output: ['A', 'p', 'p', 'l', 'e']
list2 = list([1, 3, 5])
print(list2) #Output: [1, 3, 5]
list3 = list(("Apple", "Banana", "Plum"))
print(list3) #Output: ['Apple', 'Banana', 'Plum']
list4 = list({"Yellow", "Blue", "Red"})
print(list4) #Output: ['Red', 'Yellow', 'Blue']
List comprehension
You can create lists based on existing iterables using list comprehension.
Syntax:
[Expression(item) for item in iterable if Condition]
Here,
Expression: It is the item that is being iterated.
Iterable: It can be any iterable object like lists, tuples, dictionaries, sets, or strings.
Condition: Condition checks if the item should be added to the new list or not.
For example:
#Example: 1
numbers = [2, 3, 6, 9, 18, 13]
new_numbers = [item for item in numbers if (item % 2 == 0)]
print(new_numbers) #Output: [2, 6, 18]
#Example: 2
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
new_list = [item for item in fruits if (len(item) < 5)]
print(new_list) #Output: ['Plum', 'Kiwi']
Finding the Length of the List
You can find the length of a list (number of items present in a list) using the len()
function.
For example:
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
length_of_fruits = len(fruits)
print(length_of_fruits) #Output: 5
Accessing List Items
In lists, each item has its unique index. You can access list items using indexing. Indexing starts from 0 which means the first element has an index of 0, the second element has an index of 1, and so on.
For example:
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
print(fruits[0]) #Output: Apple
print(fruits[1]) #Output: Orange
print(fruits[2]) #Output: Banana
print(fruits[3]) #Output: Plum
print(fruits[4]) #Output: Kiwi
You can also access items using negative indexing which means from the end of the list. -1 for the last item, -2 for the second-to-last item, and so on.
For example:
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
print(fruits[-1]) #Output: Kiwi
To understand negative indexing you can consider fruits[-1]
as fruits[len(fruits)-1]
.
fruits[len(fruits)-1]
fruits[5-1]
fruits[4] # Kiwi
Example:
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
print(fruits[-3]) #Output: Banana
Check Whether an Item is Present in the List
You can check whether an item is present in the list or not, using the in
keyword.
Example: 1
numbers = [1, 57, 11, 52, 13]
if 7 in numbers:
print("7 is in the list.")
else:
print("7 is not in the list.")
#Output: 7 is not in the list.
Example: 2
fruits = ["Apple", "Orange", "Banana", "Plum", "Kiwi"]
if "Plum" in fruits:
print("Plum is in the list.")
else:
print("Plum is not in the list.")
#Output: Plum is in the list.
List Slicing
You can slice a list by giving start, end and step(skip) parameters.
Syntax:
list[start : end : step]
Here,
start: This is the index where you want to begin slicing. If you don’t specify it, it starts from the beginning (index 0).
end: This is the index where you want to stop slicing. The slice will include elements up to, but not including, this index. If you don’t specify it, it goes to the end of the list.
step: The step size is how many elements you skip between slices. If you don’t mention it, it’s assumed to be 1, which means you include consecutive elements.
Example: 1
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[2:5]) #Output: [13, 6, 18]
Here, the start index is 2 and the end index is 5 which means it will print the numbers starting from index 2 i.e. 13 and ending at index (5-1) i.e. 18.
You can also use negative indexing.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[-2:5]) #Output: [18]
Here, the start index is -2 and the end index is 5 which means it will print the numbers starting from index -2 i.e. 18 and ending at index (5-1) i.e. 18.
You can calculate the negative index as numbers[-2]
as numbers[len(numbers)-2]
as explained in accessing list items.
Example: 2
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[2:]) #Output: [13, 6, 18, 54]
Here, the start index is 2 and the end index is not given. So it will print the items starting from index 2 and till the end.
You can also use negative indexing.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[-3:]) #Output: [6, 18, 54]
Example: 3
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[:4]) #Output: [1, 57, 13, 6]
Here, the start index is not given and the end index is 4. So it will print the items from start to index 3 i.e. (4-1).
You can also use negative indexing.
numbers = [1, 57, 13, 6, 18, 54]
print(numbers[:-3]) #Output: [1, 57, 13]
Example: 4
numbers = [1, 57, 13, 6, 18, 54, 62, 34]
print(numbers[1:7:2]) #Output: [57, 6, 54]
Here, the start index is 1, the end index is 7 and the step index is 2. So it will print the items starting from index 1, ending at index 6 i.e. (7-1) and with a step of 2.
numbers = [1, 57, 13, 6, 18, 54, 62, 34]
print(numbers[1:7:3]) #Output: [57, 18]
List Methods
Python provides the following built-in methods to manipulate list items.
sort()
This method is used to sort the list in ascending order or alphabetically.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.sort()
print(fruits) #Output: ['Apple', 'Banana', 'Kiwi', 'Orange', 'Plum']
What if you want to sort the list in descending order?
To sort the list in descending order, you have to give reverse=True
as a parameter in the sort method.
For example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.sort(reverse=True)
print(fruits) #Output: ['Plum', 'Orange', 'Kiwi', 'Banana', 'Apple']
Note: reverse is a parameter. Python also provides a reverse method to reverse the order of the list. Do not mistake the reverse parameter with the reverse method, as the reverse parameter is for sorting a list in descending order while the reverse method is for reversing the order of the list.
index()
This method returns the index number of the first occurrence of the given list item.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange", "Plum"]
index_of_plum = fruits.index("Plum")
print(index_of_plum) #Output: 2
append()
This method is used to append items to the end of the existing list.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.append("Grapes")
print(fruits) #Output: ['Apple', 'Banana', 'Plum', 'Kiwi', 'Orange', 'Grapes']
extend()
This method is used to add an entire list or any other collection datatype (set, tuple, dictionary) to the existing list.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
vegetables = ["Potato", "Tomato", "Spinach"]
fruits.extend(vegetables)
print(fruits)
#Output: ['Apple', 'Banana', 'Plum', 'Kiwi', 'Orange', 'Potato', 'Tomato', 'Spinach']
insert()
This method is used to insert an item to the list at the given index.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.insert(3, "Grapes") #This will insert "Grapes" at index 3.
print(fruits) #Output: ['Apple', 'Banana', 'Plum', 'Grapes', 'Kiwi', 'Orange']
copy()
This method returns a copy of the list. This will not change the original list.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
copiedList = fruits.copy()
print(fruits) #Output: ['Apple', 'Banana', 'Plum', 'Kiwi', 'Orange']
print(copiedList) #Output: ['Apple', 'Banana', 'Plum', 'Kiwi', 'Orange']
count()
This method returns how many times a certain item has appeared.
Example:
fruits = ["Apple", "Banana", "Kiwi", "Plum", "Kiwi", "Orange", "Kiwi"]
count_of_kiwi = fruits.count("Kiwi")
print(count_of_kiwi) #Output: 3
reverse()
This method is used to reverse the order of the list.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.reverse()
print(fruits) #Output: ['Orange', 'Kiwi', 'Plum', 'Banana', 'Apple']
clear()
This method is used to remove all items from a list.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
fruits.clear()
print(fruits) #Output: []
pop()
This method is used to remove the last item of the list and return the removed item.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
removed_item = fruits.pop()
print(removed_item) #Output: Orange
print(fruits) #Output: ['Apple', 'Banana', 'Plum', 'Kiwi']
Concatenating Lists
You can concatenate two or more lists using the +
operator.
Example:
fruits = ["Apple", "Banana", "Plum", "Kiwi", "Orange"]
vegetables = ["Potato", "Tomato", "Spinach"]
print(fruits + vegetables)
#Output: ['Apple', 'Banana', 'Plum', 'Kiwi', 'Orange', 'Potato', 'Tomato', 'Spinach']
Conclusion
In this blog, you’ve learned about Python lists, one of the fundamental data structures in the Python programming language.
Lists allow you to store and manipulate collections of data, whether they’re numbers, strings, or even other lists. This post covers the basics of lists, creating lists, accessing their items, list slicing and list methods.
Thanks for reading.
I created detailed Python notes while learning the language, and they’re available for only $1! Grab them here: Download Now
For more content like this click here.
You can also follow me on X(Twitter) for getting daily tips on web development.
Keep Coding!!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.