Isah Jacob

Posted on

# Why Is a List the Best Python Data Structure?

In Python, the most flexible data structure is the list. Python's data structures include four types: lists, tuples, sets, and dictionaries.

Depending on what you're building, you can use these Python data structures to solve specific tasks. This built-in data structure comes in handy when creating real-world applications.

I'll go over LIST in Python in this article. How to use it, where to use it, and how to manipulate data in a list.

## What exactly is a LIST?

A List is defined by using square brackets `[]`. Lists are used to store multiple items in a single variable. A list can have many different data type.

``````strings = ["John", "Garri", "Butter", "Maize"],
``````
``````numbers = [1, 2, 3, 4, 5],
``````
``````bolean = [True, False]
``````

A List can have list inside a list

``````List = [[1,2], [2, 3]]
``````

Each item in this list above is a list itself. it is also called a two dimentional list.

## Repetition of a List item

If, for instance, we want 5 in 50 times, The best way is to define the number we want, in this case 5, and multiply it by the number of times we want it, say 50, as shown in the example below.

``````repeating_number = [5] * 50
"""
Output: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
"""
``````

We use the asteric `*` to reapeat a number in a list.Β

## List concatenation

To concatenate a List, use a plus sign `+`.

``````repeating_number = [5] * 5
strings = ["John", "Garri", "Butter", "Maize"]
"""
Output: [5, 5, 5, 5, 5, 'John', 'Garri', 'Butter', 'Maize']
"""
``````

Every object in a list in Python can be of different types. They do not have to be of the same types.

## Iterate Through List

We can iterate through a list of numbers, a string, a list.Β Let's say we want a list of numbers, maybe 1 to 20. We cannot do [1,2,3,4,5,6,7,8 to 20]. We can use the list functions to do this.

``````value = list(range(20))
print(value)
"""
Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
``````

It is possible to iterate through the list functions. As a result, we pass an iterable to the function, which converts it to a list. To accomplish this, we use the range function `range()`. The range functions return an iterable range object. This gives us the power to loop over it. So we pass in 20 to generate a list of numbers ranging from 0 to 20.

## String combination

Because strings are iterable, we can loop over them to achieve our goal. We'll do something like this below to demonstrate the above with string.

``````string_value = list("learning list")
print(string_value)
"""
Output: ['l', 'e', 'a', 'r', 'n', 'i', 'n', 'g', ' ', 'l', 'i', 's', 't']
"""
``````

## Getting the length of a list

By using the `len()` function, we can get the number of iterms in that list.

``````print(len(string_value))
"""
Output: 13
We have 13 items on this list.
"""
``````

## Accessing Items in a List

To access an item in a list, we will use a square bracket `[]` and pass in the index.

``````print(strings[0])
"""
Output: John
"""
``````

This will return the first item in the list, John.
We can access an item at the end of a list by doing the following.

``````print(strings[-1])
"""
Output: Maize
it print Maize as the last item in the list.
"""
``````

## Modifying Items in a List

Let's modify our list so that the first and last item in the list return the new item.

``````strings[0] = "Grace" #assign Grace to the list at at index 0
strings[3] = "Jonathan" #assign Jonathan to the list at index 3
print(strings)
"""
Output: ['Grace', 'Garri', 'Butter', 'Maize', 'Jonathan']
"""
``````

## List SlicingΒ

You can slice a list using two indexes to slice a string. Consider the following example.

``````print(strings[0:2])
"""
Output: ['John', 'Garri']
"""
``````

As you can see, the slice only returns the first two items in the list. The list remains unchanged. If you do not specify either 0 or 2, the argument will be assumed to be 0.
See the list below.

``````print(print(strings[:2]) # return the first two elements in the list
print(strings[0:]) # return the exact copy of our list
print(strings[:]) # return the exact copy of our list
print(strings[::2]) # return every second elements in the list.
``````

## List Unpacking

In some cases, you may want to assign each item in a list to different variable. Let's take a look below.

``````numbers = [1, 2, 3, 4, 5]
first, second, third, fourth, fifth = numbers
print(first)
"""
Output: 1
The first, second, third, fourth and fifth are defined and added to our list.
"""
``````
``````first, second, third, fourth = numbers
print(numbers)
"""
Output: ValueError: too many values to unpack (expected 4)
"""
``````

The above will result in an error because the number of items in the list must be equal to the number of variables assigned. If it does not match, an error is thrown.

To avoid this error, follow the steps outlined below:

``````first, second, third, *other = numbers
print(first) # print 1
print(other) # print 4 and 5 as the remaining numbers
print(numbers) # print the original list

Here we are trying to get the first, second and third item and pack the rest items inside variable named other
"""
Output:
1
[4, 5]
[1, 2, 3, 4, 5]
"""
``````

If you want to get the first and the last item, you could do something like this.

``````first, *other,  last, = numbers
print(first, last) # print the first and the last item in the list
print(other) # print the rest of the items.
"""
Output:
1 5
[2, 3, 4]
"""
``````

## How to Loop Through a List

we are going to loop over a list to get an item.

``````strings = ["John", "Garri", "Butter", "Maize"]
for value in strings:
print(value)
"""
Output:
John
Garri
Butter
Maize
"""
``````

## Getting the index in a list items.

We will use the built-in function `enumerate()` to get the index of an item. The iterable object returned by the enumerate function. Each iteration will result in a tuple.

``````for value in enumerate(strings):
print(value)
"""
Output:
(0, 'John')
(1, 'Garri')
(2, 'Butter')
(3, 'Maize')
"""
``````

In this case, we get a tuple after each iteration. A tuple is similar to a list, but it can only be read. The index and value are obtained here. We see John and so on from index 0.

``````for index, value in enumerate(strings):
print(index, value)
"""
Output:
0 John
1 Garri
2 Butter
3 Maize
"""
``````

We unpack the tuple here by looping and obtaining the index and value.

## List item addition and removal

You can add items to a list in two ways.
The first option is to use the `append()` method. The append method adds an item to the end of the list.

``````strings.append("psychology")
print(strings)
"""
Output: ['John', 'Garri', 'Butter', 'Maize', 'psychology']
"""
``````

### putting an item in a specific location

If you want to add an item to a specific position in a list, you must use the `insert()` method.

``````strings.insert(0, "Abdul kereem")
print(strings)
"""
Output: ['Abdul kereem', 'John', 'Garri', 'Butter', 'Maize']
"""
``````

### Remove an item from a list.

The `pop()` method should be used to remove an item at the end of a list.

``````strings.pop()
print(strings)
"""
Output: ['Abdul kereem', 'John', 'Garri', 'Butter']
"""
``````

As you can see, the last item, maize, has been removed.
You can also remove an item by passing the index into the `pop()` method and specifying where you want it to be removed.

``````strings.pop(2)
print(strings)
"""
Output: ['Abdul kereem', 'John', 'Butter', 'Maize']
"""
``````

If you want to remove an item but don't know the index, You can use the `remove()` method and pass in the item as you can see below.

``````strings.remove("Butter")
print(strings)
"""
Output: ['Abdul kereem', 'John', 'Garri', 'Maize']
"""
``````

As you can see we removed Butter by specifying the value in the `remove()` method.

deleting an item in a list, you can use the del keyword.

``````del strings[0] # will delete Abdul kereem from the list.
del strings[0:3] # will delete the first three items in the list.
strings.clear() # will clear everything in the list
``````

find the index of a list item
Let's assume we don't know John's index.
We'll do something similar down below.

``````print(strings.index("John")
"""
Output: 1
"""
``````

If you specify an item that does not exist in the list, you will receive a value error. You can use a keyword to see if an item exists in a list.

``````if "James" in strings:
print(strings.index("James"))
"""
# this will return empty because it does not exist.
"""
``````

You can do something like this to find out how many times an item appears in a list.

``````print(strings.count("James"))
"""
Output: 1
we will get 1 because it appear only once in the item.
"""
``````

## Wrap-up

I was able to explain lists, how different types of data types can be used in a list, where to use a list, and how to manipulate data in a list in this article. I believe you have discovered something new.