Lists Data Types - List Operations, Their Impact on Scripts, and Functions.
Lists are a true fascination when it comes to managing and using data within a Python program. We are able to perform several functions and tasks with them which all help with learning List Comprehension. In Day 5, we uncover the functions of lists and how they work.
This is a well awaited topic that I’ve been eager to talk about, lists are a data type that create great fascinations for me.
The functions you can perform, the methods you can use, and all the ways you can get it to produce different information is exactly why we learn Data Structure’s and Algorithm’s, DSA1.
By this point of the course however, I only learn about how to use lists properly and what they can do so that I might gain some newer insights.
What are lists?
Lists, also known as collection data types, are used to store data in an ordered and muatable/changeable format. Think of your everyday list that you would use for shopping, task manager, and etc.
We use lists to store and manage information throughout our program. It’s important to also mention that there are different list types that we can use.
Each type has it’s own features.
Here is a small table with the different list types I have learnt so far:
| Type | Description | Example |
|---|---|---|
| List | Ordered and modifiable | items = ["Item1", 5, 12.33, False] |
| Tuple | Ordered and immutable | items = ("Item1", 5, 12.33, False) |
| Set | Unordered, unindexed, and mutable | items = {"Item1", 5, 12.33, False} |
| Dictionary | Ordered (Python 3.7+), key-value pairs | items = {"name": "Item1", "count": 5} |
Note: When we use the term ordered for lists, we mean preserving the order in which items were inserted - not logical ordering. Lists, Tuples, and Dictionaries preserve insertion order. In contrast, Sets are unordered, hence if you were to create a set with items in, with each run of the program, you could see the items shift.
Creating lists
There are a few methods we can use to assign/create a list. I want to go into as much detail as I can here, as when I went through this module, I found that knowing these do help when it comes to learning about list comprehension.
Examples:
1
2
3
4
lst = list() # This creates and empty list
lst = [] # This also creates an empty list
lst = ["Item1", "Item2", 25, 3.14, False, True, {'key':'value'}, ("Tuple"), {"Set"}]
# This creates a list with initial values (different data types including other lists can be stored).
By this point, I would recommend playing around with lists which helped me better understand them. It’s also useful to start using different built-in functions that we learnt from before, like len().
1
2
3
4
5
6
lst = ["Item1"]
print(len(lst))
# 1
print(lst)
# [Item1]
Adding Items To a List
Now that I’ve learnt how to create a list, I need to know how to append to a list or modify it.
There are several methods to doing this and instead of just writing about them, I’ll provide examples.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# .append() method
lst = [] # Create an empty list
lst.append("Item1") # You can only use this feature for one element at a time.
# To add multiple items you would have to use this several times.
print(lst) # ["Item1"]
# .insert(index,item) method
lst.insert(0,"Item2") # Insert at index 0 and push the rest to the right (insertion method)
print(lst) # ["Item2", "Item1"]
# .extend() method
lst.extend(["Item3", "Item4", "Item5",])
print(lst) # ["Item2", "Item1", "Item3", "Item4", "Item5"]
# Using Assignment Operators
lst += ["Item6", "Item7"]
print(lst) # ["Item2", "Item1", "Item3", "Item4", "Item5", "Item6", "Item7"]
# List Concatenation
new_lst = lst + ["Item8"]
print(new_lst) # ["Item2", "Item1", "Item3", "Item4", "Item5", "Item6", "Item7", "Item8"]
List Concatenation is an operation that produces a new list by combinging the items from other lists.
We can also use advanced functions like for loops to add items into a list using a loop function, with each iteration of the loop an item from a list gets added.
1
2
3
4
5
6
lst = []
for each_item in [1,2,3,4,5]: # The temporary variable 'each_item' represent each item in the list for each pass/iteration/loop
lst.append(each_item)
print(lst) # [1, 2, 3, 4, 5]
We can also add multiple items to a list using the .extend() function. It’s usually used to append a list with another lists contents; Which I’ll go over later, but for now…
1
2
3
lst = ["Item1"]
lst.extend(["Item2", "Item3"]) # See how we must still specify another list of items?
print(lst) # ["Item1", "Item2", "Item3"]
Modifying Items In a List
Remember that lists are mutable or changeable and thus, we are able to change an item in a predefined list. To perform this function, you would first call on the list, specify the item in the list or index of the item in the list you want to update, finally we would would use the assignment operator = to specify the new value.
1
2
3
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
lst[0] = "Item1"
print(lst) # ["Item1", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
All items stored within a list is stored using an index reference number, starting at 0. In addition, an item in a list that is itself a sequence, like a string data type, you can further specify an index number to access its elements.
1
2
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
print(lst[0][0]) # "C"
Removing Items From a List
At any point during our program we might want to remove an There are more than one method we can use to remove or delete items off a list and instead of diving in deep on all of them, I’ll just provide an example of what they all do.
Delete using .remove()
1
2
3
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst.remove("Item1") # Specify exact item
print(lst) # ["Item2", "Item3", "Item4", "Item5"]
Delete using .discard() This method raises no error if the item isn’t found.
1
2
3
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst.discard("Item1")
print(lst) # ["Item2", "Item3", "Item4", "Item5"]
Delete using .pop()
1
2
3
4
5
6
7
8
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst.pop(1) # Specify index to remove instead
print(lst) # ["Item1", "Item3", "Item4", "Item5"]
#OR
lst.pop() # This will automatically remove the last item from the list
print(lst) # ["Item1", "Item2", "Item3", "Item4"]
Delete using Del
1
2
3
4
5
6
7
8
9
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
del lst[0] # deletes first item
print(lst) #["Item2", "Item3", "Item4", "Item5"]
del lst[1:3] # Deleted indeces one to three
print(lst) # ["Item1", "Item5"]
del lst
print(lst) # Produces error, list deleted completely
Delete using .clear
1
2
3
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst.clear() # Clears all the contents of a list
print(lst) # []
Joining Lists
1
2
3
4
lst1 = ["Item1", "Item2"]
lst2 = ["Item3", "Item4"]
lst3 = lst1 + lst2
print(lst3) # ["Item1", "Item2", "Item3", "Item4"]
In addition to using the + operator to join lists, we can also use the .extend() to apply the contents from another list into our list.
1
2
3
4
5
lst = ["Item1"]
lst2 = ["Item2"]
lst.extend(lst2)
print(lst) # ["Item1", "Item2"]
Accessing Items In a List
Now that I’ve learnt the methods to append to a list, we need to know how to access each item in a list.
In my last post, String Data Types, I discussed the methods of unpacking, slicing, and accessing each character within a string.
We’ll now use the same methods on list data types to perform the same actions.
1
2
3
4
5
6
7
8
9
10
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
print(lst[0]) # Item1
print(lst[-1]) # Item5
#Slicing
print(lst[:-1]) # ["Item1", "Item2", "Item3", "Item4"]
print(lst[1:]) # ["Item2", "Item3", "Item4", "Item5"]
print(lst[::-1]) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
print(lst[0:5:2]) # ["Item1", "Item3", "Item5"]
Following the same method as before, I’ve been able to get used to accessing items in a list relatively easily.
Finding Items In a List
I’ve learnt about member operators before, and these can also be used on lists to check whether or not an item exists in the list.
1
2
3
lst = ["Cat", "Dog", "Fox", "Bear", "Squirrel", "Snake"]
print("Cat" in lst) # True
print("Lion" in lst) # False
I want to recall a construct that I mentioned before while discussing operators, constant and runtime sequences2. Lists, though sequencial, are mutable and therefore identical lists do not get stored in the same location.
Finding The Index Of An Item
We might want to know what the index number of an item is in a list and for that we have .index().
1
2
3
4
lst = ["Item1", "Item2"]
print(lst.index("Item1")) # 0
index_ref = lst.index("Item2")
print(index_ref) # 1
Unpacking Lists
This is very similar to the string data type which I found fairly easy to learn.
Something we missed out on the earlier post is using, what AI likes to refer to as Extended Iterable Unpacking, to unpack several items into a variable at once.
1
2
3
4
5
6
7
8
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"]
a,b,c,*d = lst
print(a) # Item1
print(b) # Item2
print(c) # Item3
print(d) # ["Item4", "Item5"]
The *variable = assignment operator produces a new list with the rest of the items in the list you specify.
Hint: With extended iterable unpacking, you can assign some items to individual variables and use a starred variable (*variable) to collect the remaining items. You can place the starred variable at the start, middle, or end, but you can only have one starred variable.
Copying Lists
Copying a list function can prove to be useful sometimes, we might want to work off a copy of the original data set and so this is available through the .copy() function.
First, we would create our original list and provide it with some data - not necessary. Then we would create a new variable and assign a copy of the list on to that variable.
1
2
3
lst = ["Item1", "Item2"]
lst2 = lst.copy()
print(lst2) # ["Item1", "Item2"]
Sorting a List
This is a topic that’s discussed in a lot of detail when it comes to learning about Data Structures and Algorithms.
That will be something I write about later in a separate series of its own.
However, for now it’s useful for me to know that we can have the contents of a list organised.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
lst = ["Item2", "Item5", "Item3", "Item4", "Item1"]
lst.sort() # This does it in ascending order
print(lst) # ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst.sort(reverse = True) # This does it in descending order
print(lst) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
# This does modify the original list
# We also have sorted() which doesn't modify the original list
lst = sorted(lst) # Ascending order
print(lst) # ["Item1", "Item2", "Item3", "Item4", "Item5"]
lst = sorted(lst, reverse = True) # Descending order
print(lst) # ["Item5", "Item4", "Item3", "Item2", "Item1"]
While revisiting this topic, the question arose to me about what the difference between .sort() and sorted() actually is.
The best explanation I could provide on this, even after spending sometime going back and forth with AI to explain the concept, is that .sort() mutates the original list and sorted() creates and rebinds a new list when we assign it to the same variable as the old one.
I wanted to make sure that I have this explained as best as I can as it could help later one.
Think of one going in to a list and rearranging the items, the other as temporarily creating a new list and then returning that being arranged or ordered.
ChatGPT did not like it when I would use the phrase ‘overwrite over the existing list variable’ and keeps insisting that we say it is being re-bound to the old variable.
The original list is left unchanged and becomes unreferenced.
Reversing a List
We can also have the contents of our list be reversed without having to sort them using the .reverse() function.
1
2
3
lst = ["Item 2","Item 1 ","Item 3"]
lst.reverse()
print(lst) # ["Item 3", "Item 1", "Item 2"]
Note how this just printed it all out in reverse rather than ordering.
Counting Items In a List
This is different from .len() as instead of counting the total number of items, .count() will count the occurance of an item you specify in a list.
1
2
3
lst = ["Item 2","Item 1 ","Item 3", "Item 3"]
print(lst.count("Item 3")) # 2
Changing a Collection Data Type
While learning about tuples, I came across the idea that you can change one collection data type into another. I probably should make mention of this later on, however, when I was going over the course contents the first time round I felt like this would be good information to know of when I first learnt of lists. This helps keep it in mind when I went over it the second time.
1
2
3
4
5
lst = ["Item1", "Item2", "Item3", "Item4", "Item5"] # Create a list with initial values
lst = tuple(lst) # Convert the list into a tuple
print(lst) # ("Item1", "Item2", "Item3", "Item4", "Item5")
This same approach works with other collection data types as well. In many cases, these conversions are interchangeable and simply depend on what you want to achieve.
I found this particularly useful when converting a list into a set, since sets automatically remove duplicate values, or when locking in data by converting a list into an immutable structure.
Summary
By the end of writing this post, I’ve gained a deeper insight into the functions available for the traditional list data types and how they can be applied.
Though this would be my second pass over the course, I can now better reflect on the importance of each function and how they intereact with list data.
I’ll be going over Tuples next, and a lot of the functions will be the same. However, since tuples are immutable, some operations would behave differently.
I’m more after repetition and understand of functions, than I am with doing tasks with them. As I think that this will aid my creativity from the understandings I gain.