Python Data Structures: Lists

Python Data Structures: Lists

Have you heard of the four fundamental bedrock of Python? And when I say fundamental, I mean you literally cannot do without them in your code.

It’s very pertinent to familiarize yourself with the data structures birthed with Python as they run through every aspect of your code, and are required to store data, improve your code and perform various functionalities.

These data structures are employed based on their use cases and mutability. Before we get started, I will implore you to get a note and pay close attention as I unravel certain mysteries behind one of these four very important fundamentals.

Lists “[]”

What would we all do without Python lists, I tend to ask myself? Best believe, we have come across this word various times from our classroom days, down to the notes we take to the grocery store to get junk/foodstuffs to last us for the week.

But what are their uses in Python?

Python lists are containers that hold tiny bits to large chunks of data to be reused later in our code. Python lists rely on the principle of order and mutability.

In terms of the order, every piece of data entered into the list is allocated a specific number referred to as an index, which represents its position in the list, and mutability in the sense of adding, removing and altering data entered into every one of these data structures.

Indexing

When performing counting operations in Python, the position of the first item in the list starts with an index of 0 and runs down to the last item entered into the list.

food_items = ['Rice', 'Yoghurt', 'Beans', 'Flour', 'Tomatoes']

This above is a typical representation of the physical structure of a list. Dissecting this list we can locate the index of each item in this list of food_items.

#Rice – takes up the “0” index being the first item in the list.

#Yoghurt – has an index of 1

#Beans- an index of 2

#Flour and tomatoes – an index of 3 and 4 respectively.

This index plays a huge role in accessing, modifying and extrapolating data from your list.

Nested Lists

Another interesting fact about lists is their ability to be nested in one another. This means combining two or more lists as one list, but with each list still maintaining its properties.

food_items = ['Rice', 'chicken', 'Beans', 'Flour', 'Tomatoes']

drinks = ['Coca-Cola', 'ice-cream', 'Fanta', 'red wine']

ingredients = ['salt', 'pepper', 'ginger']

all_food-items = [food_items, drinks, ingredients]

This is a typical representation of nested lists.

Basic List Operations

Various list operations are used to tweak and manipulate our input for a preferred output of our choice. What is the principle behind this whole concept? This principle stresses an important aspect of lists which is mutability; lists can be altered either by adding or deleting elements from it.

1) append()

The list.append() function is used to add more elements to our list. This particular operation takes in one input at a time and appends this input to the list after the last element on the list.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
friends.append('Fikewa')
friends.append('Hadassah')
print(friends)

#Output
['Stella', 'Nicole', 'Soffiyah', 'Busayo', 'Fikewa', 'Hadassah']

2) extend()

This is an upgraded version of the append() function. It takes more than one input at a time, which is placed in a list and passed into the operator.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
friends.extend(['David', 'Sammy'])
print(friends)
#Output
['Stella', 'Nicole', 'Soffiyah', 'Busayo', 'David', 'Sammy']

3) remove()

Just like we treated adding and appending items to lists, we can also remove items from our lists using the list.remove() operator. This operation can only take one argument at a time. Even if there are many occurrences of that element in the list, it only takes out the first occurrence of that element.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
friends.remove('Stella')
print(friends)

#Output
['Nicole', 'Soffiyah', 'Busayo']

#Second case

items = [2, 3, 2, 5, 7, 8, 2, 3, 6, 8]
items.remove(2)
print(items)

#Output
[3, 2, 5, 7, 8, 2, 3, 6, 8]

4) min() and max()

This operation iterates through the list and returns the minimum(lowest) and maximum(highest) values in the list.

numbers = [2, 3, 6, 7, 8, 9]

Print(min(numbers))
#output
2 
print(max(numbers)) 
#output
9

5) count()

Assuming you have a list with several repeated items, the count() operation returns the total occurrence of that item.

items = [2, 3, 2, 5, 7, 8, 2, 3, 6, 8]
print(items.count(2))

#output
3

6) len()

This operation returns the number of items in a list, however, this uses the normal number system to count, starting from 1 down to the last number.

items = [2, 3, 2, 5, 7, 8, 2, 3, 6, 8]
print(len(items))

#Output
10

7) concatenate

Just like in strings where we can perform the concatenating operation which implies adding and joining two strings together, we can also apply this to two or more different lists. This operation is represented by using the “+” sign in between two or more lists.

items = [2, 3, 2, 5, 7, 8, 2, 3, 6, 8]

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
print(items + friends)

#Output
[2, 3, 2, 5, 7, 8, 2, 3, 6, 8,'Stella', 'Nicole', 'Soffiyah', 'Busayo']

8) multiply

This operation significantly increases the number of lists by a provided factor when the multiplication operator “*” is called on it.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']

Print(friends*2)  
#This automatically multiplies the entire list by 2, increasing each item by 2, and this new list starts at the end of the old list.

#output
['Stella', 'Nicole', 'Soffiyah', 'Busayo', 'Stella', 'Nicole', 'Soffiyah', 'Busayo']

9) index()

We touched on this aspect previously but let's dive even deeper. The list uses the index() method to pull out an item from its container.

In Python when counting elements in a list, string down to a dictionary and the like, we take the first number or position as a zero, followed by the rest. However, the list index is important when we perform list slicing.

Let's have an example, to fetch the position of an element in the list we call the index() method on it, with one argument of an item in this list.

Note: if there is more than one occurrence of that element it will only fetch the first occurrence it meets.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
print(friends.index('Soffiyah')

#Output
2
#However, if you want particular in a particular position, you use this method “[]”
friends[3]
#This outputs the element at the index of 3, starting from 0,1,2,3
#output
Busayo

10) slice

This is a very resourceful method we can use to grab a chunk of data from a list, and this works on the principle of list.index(). Pay close attention because this is a bit technical.

This slice method is of the form list[x:y], where x and y are two indexes. The “x” index is the starting position where you might wanna start fetching data from, let's say position0. While the “y” index might appear to you as the endpoint at the first glance but it is not.

When using the slice method the last index is never taken into consideration, the items fetched stop right before it. Okay, this feels like Greek so let's have us an example.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']

cropped_list = friends[0:2]

#This prints out the items from index 0 to the item before index 2. Hence our output would be
print(cropped_list)

['Stella', 'Nicole']

However, to fetch all the items or from any section down to the last items you can use these two methods.

-friends[x:(last index +1)]

Now from our rule, we know that this method fetches the item before the last index. If we had four items and we wanted to fetch from the third item to the fourth item we can simply use the slice method, but instead of putting in four as the last index we put in five, because we know it would stop at the last item before the fifth one which is the fourth item. And this would return the last item on our list.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']

preferred_item = friends[1:4]
print(preferred_item)

#output
['Nicole', 'Soffiyah', 'Busayo']

-Another method and the most used is leaving the last index blank; this automatically fetches the indicated range of selection down to the last index.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
preferred_item = friends[1:]

print(preferred_item)
#output
['Nicole', 'Soffiyah', 'Busayo']

11) reverse()

This is kinda similar to the slice method except that here we are reversing the order and taking the last element to be the first down to the first being the last.

This is represented thus, Friends[::-1], we use a double colon here and also a '–' sign to indicate a reversal of the flow, that is a jump backward by 1.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
print(friends[::-1])

['Busayo', 'Soffiyah', 'Nicole', 'Stella']

12) insert()

This function is a more upgraded version of extend and append, here, you can insert an item to a preferred position of your choice. It takes in two arguments, the first argument being the preferred location and the second argument being the item to be inserted into the list.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
friends.insert(3, “Dami”)

#This automatically places Dami in the third position and moves the former element to the next position which is the fourth position.

Friends = ['Stella', 'Nicole', 'Dami','Soffiyah', 'Busayo']

13) pop() and clear()

The pop() method takes the index of an element and completely removes it from the list, while the clear() operations when called on a list, completely clear the list of all its items.

friends = ['Stella', 'Nicole', 'Soffiyah', 'Busayo']
friends.pop(2)

#Output
friends = ['Stella', 'Nicole', 'Busayo']
friends.clear()

#Output
friends = []

14) sort()

This is used on a list with identical items, say numbers or alphabets, it arranges them in alphabetical order.

number = [2, 2, 2, 4, 5, 6, 3]
letter = ['a', 'c', 'b']

number.sort()
letter.sort()

print(letter)
print(number)

#output
['a', 'b', 'c']
[2, 2, 2, 3, 4, 5, 6]

I believe from this article you should now have a sound understanding of lists and their various basic operations.

Like, comment, share and follow if you enjoyed this article.

Don't forget to follow me on all my socials.

Twitter: Chizobaonorh_

LinkedIn: Chizoba Ononlememen

Email: Rewardonorh@gmail.com