Python Lists
- Read
- Discuss
Introduction
A Python list can be considered as a cargo train to hold different types of goods for a specific time period. Each carriage in the train represents an element in the list, and each part can hold a different type of good.
For example, let’s say you have a list called cargo_train that represents a train carrying various types of goods. You could create this list in Python like this:
cargo_train = ['apples', 'oranges', 'bananas', 'wheat']
In this example, the list cargo_train contains 4 elements: ‘apples’, ‘oranges’, ‘bananas’, and ‘wheat’. The indexing starts from zero. These elements are stored in a particular order, so we can say that ‘apples’ are on the first carriage on the train with index 0, ‘oranges’ are on the second carriage with index 1, and so on.
You can access the elements of the list using their indexes. For example, to access the third carriage on the train (which is carrying bananas), you can use the following code:
banana_carriage = cargo_train[2]
The above code will assign the value ‘bananas’ to the variable banana_carriage.
You can also use indexes to modify the elements of the list. For example, to change the type of goods in the fourth carriage to ‘rice’, you can use the following code:
cargo_train[3] = 'rice'print(cargo_train)
Output:
['apples', 'oranges', 'bananas', 'rice'].
Now on the 3rd Index we have Rice:
Following are properties of Python sets:
- Ordered: Lists maintain the order of data insertion
- Mutable: We can modify list items
- Heterogeneous: Lists can contain different types of data
- Duplicates: Lists allow duplicate items
Types of Data That Can Be Stored in Python Lists
Lists are a type of data structure in Python that can hold any type of data. These items can be of any data type, such as numbers, strings, or other lists.
For example, you could create a list of numbers like this:
numbers = [1, 2, 3, 4, 5]
Or you could create a list of strings like this:
colors = ['red', 'orange', 'yellow', 'green', 'blue']
You can even create a list of lists, like this:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
The above is also called 2d-arrays in other languages.
So, the type of data that is good to be stored in a Python list really depends on what you want to do with that data. Lists are a very flexible data type, and they can store almost any kind of data.
List Built in Functions
In the following list we have listed the most commonly used List functions.
Function | Description |
append(x) | Adds an item to the end of the list |
extend(iterable) | Adds all the items from an iterable (e.g. list, tuple) to the end of the list |
insert(i, x) | Inserts an item at a given position |
remove(x) | Removes the first item from the list that has the same value as x |
pop([i]) | Removes and returns the item at the given position, or the last item if not specified |
clear() | Removes all items from the list |
index(x) | Returns the index of the first item that has the same value as x |
count(x) | Returns the number of items in the list that have the same value as x |
sort() | Sorts the items in the list in ascending order |
reverse() | Reverses the order of the items in the list |
copy() | Returns a shallow copy of the list |
Implement Python Lists
We have already seen how to create a list and how to access elements from a python list.
Let’s take a look at some use cases of Python lists
Imagine you are building a chatbot that maintains a list of users who are currently online. You can use a Python list to store the names of the online users, and update the list in real-time as users log in and out of the chatbot. Here is some example code that demonstrates how you might implement this:
online_users = []
def log_in(username):
if username not in online_users:
online_users.append(username)
print(f"{username} has logged in.")
def log_out(username):
if username in online_users:
online_users.remove(username)
print(f"{username} has logged out.")
# Example usage
log_in("Alice")
# prints "Alice has logged in."
log_in("Bob")
# prints "Bob has logged in."
log_out("Alice")
# prints "Alice has logged out."
# Print the current list of online users
print(online_users) # prints ["Bob"]
Output:
Alice has logged in.
Bob has logged in.
Alice has logged out.
['Bob']
Iterating over data
Lists are very useful for looping and iterating over data. For example, you might use a list to store a collection of strings, and then use a for loop to iterate over the list, performing some operation on each string
You can use for loop to iterate over the elements of a online users.
# Define a list of names
online_users = ['Alice', 'Bob', 'Charlie', 'Dave']
# Iterate over the names
for name in online_users:
# Print each name
print(name)
This code will output the following:
Alice
Bob
Charlie
Dave
In the above example, the for loop iterates over the elements of the online users. On each iteration, the value of the current element is assigned to the variable name, and the loop body is executed. In this case, the loop body is simply a single line of code that prints the value of name.
You can use a for loop to execute a task for each element in a list, such as printing the elements or manipulating the data in some way. This is a very common operation in Python, and it is often used to process large amounts of data stored in lists.
Use Cases of Python Lists
- Storing and manipulating data that needs to be accessed in a specific order
- Iterating over data
- Storing data that needs to be changed or modified
- Storing data that doesn’t fit neatly into any other data type
The uses cases of Python lists are endless. Let’s take a look at an example of nested lists.
Nested Lists in python
A nested list in Python is a list that contains other lists as its elements. Here is an example of a nested list:
my_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, my_list is a list with three elements, each of which is itself a list.
You can access the elements of a nested list using multiple indices. For example, to access the element 5 in the list above, you would use the following code:
element = my_list[1][1]
This code would access the second element of my_list, which is the list [4, 5, 6], and then access the second element of that list, which is the number 5.
You can also modify the elements of a nested list using multiple indices. For example, to change the element 5 to the number 10, you would use the following code:
my_list[1][1] = 10
You can also use loops to iterate over the elements of a nested list. For example, to print all of the elements of the list above, you could use a nested for loop like this:
for sublist in my_list:
for element in sublist:
print(element)
There are several benefits to using Python lists:
- Lists are ordered: Lists maintain the order of the items that you add to them. This can be useful when you need to access or manipulate the items in a specific order.
- Lists are mutable: Lists are mutable, which means that you can change their contents (such as adding or removing items) after they are created. This can be useful when you need to modify a list over time.
- Lists are versatile: Lists can store a wide range of data types, including numbers, strings, and even other lists. This makes them a very versatile data type that can be used in a variety of different situations.
- Lists are easy to work with: Lists have a number of built-in methods (such as sort(), reverse(), and pop()) that make it easy to manipulate and work with the data stored in them.
Limitations of Python Lists
Python lists are a very useful and adaptable data type, but they are not always the best choice for every situation. Here are a few drawbacks to using lists:
- Lists are inefficient for very large data sets
- Lists do not have a fixed structure
- Lists are not as fast as some other data structures
Overall, while Python lists are a very useful data type, they are not always the best choice for every situation. It is important to consider the precise needs of your application and choose the data structure that is best fit for your needs.
Comparison operators allow you to compare two values and return a Boolean value indicating whether the comparison is True or False. Python has the following comparison operators: