Lesson 6: Lists

Composite Nature: List is a very useful composite data structure meaning it can hold multiple types of data. You can also call it a data sequence.

Unlike dictionaries lists have an index order. This means every element inside a list has an index and this doesn’t change unless you change it. For some other data structures such as dictionaries this can be different. For instance dictionaries don’t have indexes for the keys inside them so you can’t say 2nd or 3rd element as such an order doesn’t exist. Think of it like having a bag of mixed goods with no particular order. We will look at dictionaries in more detail in the upcoming lessons.

Indexing: It’s important to note that indexing for lists starts with 0 (zero). Meaning first element in the list is actually zeroth element in Python world. This is important to remember.

Mutability: Lists are also mutable and this means you can add and remove their elements as you wish. Let’s look at some examples.

Function 1: .append()

append() is probably one of the most commonly used list method. It’s used for adding elements to lists.

Used Where?

Lists are very commonly used data sequences in Python. They can be used with pretty much anything that’s related to data.
 
  • .append(): used for adding elements to a list
  • .insert(): used for inserting element to a particular index of the list
  • .index(): used to show the index of an element
  • .clear(): clears all the elements of the list
  • .remove(): used for removing an element of the list
  • .reverse(): reverses the order inside the list
  • .count(): used for counting how many elements there are in the list
  • sum(): sums all the elements in the list
  • min(): shows the element with lowest value in the list
  • max(): shows the element with highest value in the list

Syntax do(s)

1) Lists are constructed using brackets: []

2) Elements inside your list should be separated with commas.

3) Syntax regarding data types need to be followed inside the lists. So if you have a string, it should be in quotes and integer, float and bool types shouldn’t be in quotes.

Syntax don't(s)

1) elements inside your list should be separated with commas

2) 

Below is a list consisting of different types of elements. It’s a perfect example to demonstrate different nuances of the lists. Let’s see.

Example 1

>>> p_datatypes = [“Soho”, “Gramercy”, 23, 51, False, “False”, “22”]
>>> print(p_datatypes)

“Soho”, “Gramercy”, 23, 51, False, “False”, “22”

1) First of all we can see there are different types of data inside the list: p_datatypes. These are string, integer, boolean, then string again.

2) Last two elements of the list are actually strings although they might look like bool and integer type since they are inside quotation marks they are registered as strings in Python.

3) Finally when we look at the indexing of the list, index 0 is the first element “Soho” and index 6 element is “22”, both strings. Although there are actually 7 elements in the list, index goes up to 6 since it starts with 0.

Accessing Elements: List elements can be accessed with their index number in brackets.

p_datatypes = [“Soho”, “Gramercy”, 23, 51, False, “False”]

for instance to access the first element “Soho” the correct syntax would be: 

p_datatypes[0]

and to reach 23:

p_datatypes[2]

Let’s look at some examples.

Last element of the below list is a boolean with the value: False. We will access it inside the print function below.

Example 2

>>> p_datatypes = [“Soho”, “Gramercy”, 23, False]
>>> print(p_datatypes[3])

False

And accessing the first element of the list.

Example 3

>>> p_datatypes = [“Soho”, “Gramercy”, 23, False]
>>> print(p_datatypes[0])

“Soho”

Tips

1- Reverse Indexing: Elements in the list can also be called starting from the end which is usually called reverse indexing. Unlike regular indexing reverse indexing doesn’t start with 0 and starts with -1.

So to access the last element of p_datatypes:
p_datatypes[-1] can be used and it would give you the last element of the list.

2- Similarly, p_datatypes[-2] would give you the second element from the end and so on.

This approach can offer great benefits in appropriate situations. It can be more practical and efficient to use since you don’t have to count the number of elements inside the list to access the last item or other items from the end. Another advantage would be evident if the size of the list is changing, again you wouldn’t have to bother with counting from the beginning to reach the last elements.

Let’s look at the examples.

Example 4

>>> p_datatypes = [“Soho”, “Gramercy”, 23, False]
>>> print(p_datatypes[-1])

False

Now let’s see an example where .append() method is used to add a new element to the end of the list.

Example 5

>>> p_datatypes = [“Soho”, “Gramercy”]
>>> p_datatypes.append(“Tribeca”)
>>> print(p_datatypes)

p_datatypes = [“Soho”, “Gramercy”, “Tribeca”]

Function 2: .insert()

.insert() is another useful method for lists. It can be used for inserting an element to the list by indicating index number.

Let’s see an example.

.insert() method takes two arguments inside its parenthesis: first, the index that the new element is desired to be inserted at, second, the new element.

Example 6

>>> p_datatypes = [“Soho”, “Gramercy”]
>>> p_datatypes.insert(0, “Tribeca”)
>>> print(p_datatypes)

p_datatypes = [“Tribeca”, “Soho”, “Gramercy”]

Example 7

>>> p_datatypes = [“Soho”, “Gramercy”]
>>> p_datatypes.insert(1, “Tribeca”)
>>> print(p_datatypes)

p_datatypes = [“Soho”, “Tribeca”, “Gramercy”]

Function 3: .index()

.index() helps identify the index number of an element.

Let’s see an example.

And here is a similar example for an empty dictionary assignment.

Example 8

>>> lst = [1, 33, 5, 55, 1001]
>>> a = lst.index(55)
>>> print(a)

3

Function 4: .clear()

.clear() method will clear all the elements of a list. 

Example 9

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.clear()
>>> print(lucky_numbers)

[]

Function 5: .remove()

.remove() method will help you remove a specific element from a list. 

Example 10

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.remove(101)
>>> print(lucky_numbers)

[5, 55, 4, 3, 42]

Function 6: .reverse()

.reverse() method will reverse the order of elements in a list. 

Example 11

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> lucky_numbers.reverse()
>>> print(lucky_numbers)

[42, 101, 3, 4, 55, 5]

Function 7: .count()

.count() method is useful to find out how many occurrences there are in a list for a specific element. 

In the example below, you can see that integer 5 is counted inside the list lucky_numbers. When we print, we get the output 1, meaning 5 occurs once in the list.

Example 12

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(lucky_numbers.count(5))

1

1 however, is not even in the list, so the output is 0.

Example 13

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(lucky_numbers.count(1))

0

Function 8: sum()

.sum function will give you the total sum of a list numbers. 

Example 14

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(sum(lucky_numbers))

210

Function 9: min()

min() function will show you the minimum value of a list. 

Let’s see an example.

Example 15

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(min(lucky_numbers))

5

Function 10: max()

max() function will show you the maximum value of a list. 

Let’s see an example.

Example 16

>>> lucky_numbers = [5, 55, 4, 3, 101, 42]
>>> print(max(lucky_numbers))

101

Advanced Concepts (Optional)

There are some other methods and Python functions we will see in the upcoming lessons. Some of them deserve their own lesson for the sake of keeping this lesson at a reasonable length.

These methods and functions can have a small twist in the way they work or cover a more broad functional perspective.

Let’s summarize them here ahead of the next lessons.

1- .sort()

2- .find()

3- .pop()

4- len() (shared by many other data types)

5- zip()

6- map()

7- filter()

8- List Comprehension (a super practical and useful approach to lists which we will cover later.)

Shuffle Method

You can shuffle your lists in place thanks to random library.

random library is a default library that comes with Python and it has great features that everyone can benefit from (randrange and randint are some popular ones.)

But it also has a fantastic lesser known method called shuffle.

Using shuffle you can shuffle your lists in place. All you have to do is import random library and then use random.shuffle(sequence) syntax.

Check out this example:

import random

lst = [1,2,3,4,5,6,7,8,9,10]

random.shuffle(lst)
print(lst)

Output:

[7,3,5,2,6,8,4,1,9]

So, that’s about it. Lists are very handy and highly utilized in Python programming. So, congratulations on covering this fundamental topic.

We have some great exercises you can check out. As you code around and play with the concepts you will have a much deeper understanding of main Python concepts and programming in general which is usually the path to building amazing things.

Here are the List exercises:

Next Lesson:

Python Tuples

Allegory of Seasons (winter) by Sebastian Vrancx

“Have you installed Python yet?”

Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.
Sandra Files