In this tutorial, we learned about Python Lists and how to create, access, modify, and manipulate them. We also explored some of the common operations that can be performed on Python lists, such as adding or removing items and looping through a list.
Introduction to Python Lists
Python Lists are a collection of ordered and changeable items, which can be of any data type like integers, strings, or even other lists.
In Python, a list is a collection of items that are ordered and changeable. Lists are denoted by square brackets []
and each item in the list is separated by a comma ,
.
Creating a List
To create a list in Python, you simply enclose a comma-separated sequence of values within square brackets.
Example
the following code creates a list of numbers:
first_list = [1, 2, 3, 4, 5]
Accessing List Elements
Python lists are indexed and the indexing starts from 0. To access an element in a list, we can refer to its index number within square brackets [].
Example
To access the first element of the first_list list above, you would use the following code:
first_element = my_list[0]
Output
1
You can also use negative indexes to access elements from the end of the list. For example, to access the last element of the first_list list, you would use the following code:
last_element = my_list[-1]
Output
2
Changing List Items
Python lists are mutable. It means that we can change their elements after they have been created. To change the value of an element, we can simply refer to its index number and assign a new value to it.
first_list = [1, 2, 3, 4, 5] first_list[1] = "10" print(first_list)
Output
[1, 10, 3, 4, 5]
List Length
To find out how many items a list has, we can use the len() function.
first_list = [1, 2, 3, 4, 5] print(len(first_list))
Output
5
Adding Items to a List
We can add new items to a list by using the append() method. The new item will be added to the end of the list.
first_list = [1, 2, 3, 4, 5] first_list.append("11") print(first_list)
Output
[1, 2, 3, 4, 5, 11]
Removing Items from a List
To remove an item from a list, we can use the remove() method. We need to specify the value of the item that we want to remove.
first_list = [1, 2, 3, 4, 5] first_list.remove("3") print(first_list)
Output
[1, 2, 4, 5, 11]
Looping Through a List
We can loop through all the items in a list by using a for loop.
first_list = [1, 2, 3, 4, 5] for item in first_list: print(item)
Output
1, 2, 3, 4, 5
List Comprehension
List comprehension is a concise way of creating a new list by performing an operation on each item in an existing list.
first_list = [1, 2, 3, 4, 5] new_list = [item * 2 for item in first_list] print(new_list)
Output
[2, 4, 6, 8, 10]