Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
The Python Workshop Second Edition - Second Edition

You're reading from  The Python Workshop Second Edition - Second Edition

Product type Book
Published in Nov 2022
Publisher Packt
ISBN-13 9781804610619
Pages 600 pages
Edition 2nd Edition
Languages
Authors (5):
Corey Wade Corey Wade
Profile icon Corey Wade
Mario Corchero Jiménez Mario Corchero Jiménez
Profile icon Mario Corchero Jiménez
Andrew Bird Andrew Bird
Profile icon Andrew Bird
Dr. Lau Cher Han Dr. Lau Cher Han
Profile icon Dr. Lau Cher Han
Graham Lee Graham Lee
Profile icon Graham Lee
View More author details

Table of Contents (16) Chapters

Preface 1. Chapter 1: Python Fundamentals – Math, Strings, Conditionals, and Loops 2. Chapter 2: Python Data Structures 3. Chapter 3: Executing Python – Programs, Algorithms, and Functions 4. Chapter 4: Extending Python, Files, Errors, and Graphs 5. Chapter 5: Constructing Python – Classes and Methods 6. Chapter 6: The Standard Library 7. Chapter 7: Becoming Pythonic 8. Chapter 8: Software Development 9. Chapter 9: Practical Python – Advanced Topics 10. Chapter 10: Data Analytics with pandas and NumPy 11. Chapter 11: Machine Learning 12. Chapter 12: Deep Learning with Python 13. Chapter 13: The Evolution of Python – Discovering New Python Features 14. Index 15. Other Books You May Enjoy

List methods

Since a list is a type of sequence, it supports all sequence operations and methods.

Lists are one of the best data structures to use. Python provides a set of list methods that makes it easy for us to store and retrieve values to maintain, update, and extract data. These common operations are what Python programmers perform, including slicing, sorting, appending, searching, inserting, and removing data.

You will learn about these handy list methods in the following exercises.

Exercise 22 – basic list operations

In this exercise, you are going to use the basic functions of lists to check the size of a list, combine lists, and duplicate lists:

  1. Open a new Jupyter notebook.
  2. Type the following code:
    shopping = ["bread","milk", "eggs"]
  3. The length of a list can be found using the global len() function:
    print(len(shopping))

Note

The len() function returns the number of items in an object. When the object is a string, it returns the number of characters in the string.

The output is as follows:

3
  1. Now, concatenate two lists using the + operator:
    list1 = [1,2,3]
    list2 = [4,5,6]
    final_list = list1 + list2
    print(final_list)

You will get the following output:

[1, 2, 3, 4, 5, 6]

As you can see, lists also support many string operations, one of which is concatenation, which involves joining two or more lists together.

  1. Now, use the * operator, which can be used for repetition in a list, to duplicate elements:
    list3 = ['oi']
    print(list3*3)

It will repeat 'oi' three times, giving us the following output:

['oi', 'oi', 'oi']

You are now familiar with some common operations that Python programmers use to interact with lists.

Accessing an item from a list

Just like other programming languages, in Python, you can use the index method to access elements in a list. You should complete the following exercise while continuing with the previous notebook.

Exercise 23 – accessing an item from shopping list data

In this exercise, you will work with lists and gain an understanding of how you can access items from a list. The following steps will enable you to complete this exercise:

  1. Open a new Jupyter Notebook.
  2. Enter the following code in a new cell:
    shopping = ["bread","milk", "eggs"]
    print(shopping[1])

The output is as follows:

milk

As you can see, the milk value from the shopping list has an index of 1 since the list begins from 0.

  1. Now, access the first index and replace it with banana:
    shopping[1] = "banana"
    print(shopping)

The output is as follows:

['bread', 'banana', 'eggs']
  1. Type the following code in a new cell and observe the output:
    print(shopping[-1])

The output is as follows:

eggs

The output will print eggs – the last item.

Just like with strings, Python lists support slicing with the : notation in the format of list[i:j], where i is the starting element and j is the last element (non-inclusive).

  1. Enter the following code to try out a different type of slicing:
    print(shopping[0:2])

This prints the first and second elements, producing the following output:

['bread', 'banana']
  1. Now, to print from the beginning of the list to the third element, run the following:
    print(shopping[:3])

The output is as follows:

['bread', 'banana', 'eggs']
  1. Similarly, to print from the second element of the list until the end, you can use the following:
    print(shopping[1:])

The output is as follows:

['banana', 'eggs']

Having completed this exercise, you are now able to access items from a list in different ways.

Adding an item to a list

In the previous section and Exercise 23 – accessing an item from shopping list data, you learned how to access items from a list. Lists are very powerful and are used in many circumstances. However, you often won’t know the data your users want to store beforehand. Here, you are going to look at various methods for adding items to and inserting items into a list.

Exercise 24 – adding items to our shopping list

The append method is the easiest way to add a new element to the end of a list. You will use this method in this exercise to add items to our shopping list:

  1. In a new cell, type the following code to add a new element, apple, to the end of the list using the append method:
    shopping = ["bread","milk", "eggs"]
    shopping.append("apple")
    print(shopping)

Let’s see the output:

['bread', 'milk', 'eggs', 'apple']

The append method is commonly used when you are building a list without knowing what the total number of elements will be. You will start with an empty list and continue to add items to build the list.

  1. Now, create an empty list, shopping, and keep adding items one by one to this empty list:
    shopping = []
    shopping.append('bread')
    shopping.append('milk')
    shopping.append('eggs')
    shopping.append('apple')
    print(shopping)

Here’s the output:

['bread', 'milk', 'eggs', 'apple']

This way, you start by initializing an empty list, and you extend the list dynamically. The result is the same as the list from the previous code. This is different from some programming languages, which require the array size to be fixed at the declaration stage.

  1. Now, use the insert method to add elements to the shopping list:
    shopping.insert(2, 'ham')
    print(shopping)

The output is as follows:

['bread', 'milk', 'ham', 'eggs', 'apple']

As you coded in Step 3, you came across another way to add an element to a list: using the insert method. The insert method requires a positional index to indicate where the new element should be placed. A positional index is a zero-based number that indicates the position in a list. You can use ham to insert an item in the third position.

In the preceding code, you can see that ham has been inserted in the third position and shifts every other item one position to the right.

Having concluded this exercise, you are now able to add elements to our shopping list. This proves to be very useful when you get data from a customer or client, allowing you to add items to your list.

Exercise 25 – looping through a list

It’s common to generate new lists by looping through previous lists. In the following exercise, you will loop through a list of the first 5 primes to generate a list of the squares of the first 5 primes:

  1. In a new cell, enter the first 5 primes in a list called primes.
    primes = [2, 3, 5, 7, 11]
  2. Now create an empty list, primes_squared, then loop through the primes list and append the square of each prime, as follows:
    primes_squared = []
    for i in primes:
        primes_squared.append(i**2)
    print(primes_squared)

The output is as follows:

[4, 9, 25, 49, 121]

This is the standard way to loop through lists to generate new lists. In Chapter 7, Becoming Pythonic, you will learn about a new way of using list comprehensions.

Now, let’s examine matrices as nested lists.

Matrices as nested lists

Most of the data we store in the real world is in the form of a tabular data table – that is, rows and columns – instead of a one-dimensional flat list. Such tables are called matrices or two-dimensional arrays. Python (and most other programming languages) does not provide a table structure out of the box. A table structure is simply a way to present data.

What you can do is present the table structure shown in Figure 2.3 using a list of lists; for example, let’s say you want to store the following fruit orders using a list:

Figure 2.3 – A representation of lists of lists as a matrix

Figure 2.3 – A representation of lists of lists as a matrix

Mathematically, you can present the information shown in Figure 2.3 using a 2 x 3 (2 rows by 3 columns) matrix. This matrix would look like this:

Figure 2.4 – A matrix representation of data

Figure 2.4 – A matrix representation of data

In the next exercise, you will learn how to store this matrix as a nested list.

Exercise 26 – using a nested list to store data from a matrix

In this exercise, you will look at working with a nested list, storing values in it, and accessing it using several methods:

  1. Open a new Jupyter notebook.
  2. Enter the following code in a new cell:
    m = [[1, 2, 3], [4, 5, 6]]

We can store the matrix as a series of lists inside a list, which is called a nested list.

We can now access the elements using the [row][column] variable notation.

  1. Print the element indexed as the first row and first column:
    print(m[1][1])

The output is as follows:

5

It prints the value of row 2, column 2, which is 5 (remember, we are using a zero-based index offset).

  1. Now, access each of the elements in the nested list matrix by retaining their reference index with two variables, i and j:
    for i in range(len(m)):
      for j in range(len(m[i])):
        print(m[i][j])

The preceding code uses a for loop to iterate twice. In the outer loop (i), we iterate every single row in the m matrix, and in the inner loop (j), we iterate every column in the row. Finally, we print the element in the corresponding position.

The output is as follows:

1
2
3
4
5
6
  1. Use two for..in loops to print all the elements within the matrix:
    for row in m:
      for col in row:
        print(col)

The for loop in the preceding code iterates both row and col. This type of notation does not require us to have prior knowledge of the matrix’s dimensions.

The output is as follows:

1
2
3
4
5
6

You now know how a nested list stored as a matrix works, and how to access values from nested lists. In the next activity, you will implement these concepts to store employee data.

Activity 6 – using a nested list to store employee data

In this activity, you are going to store table data using a nested list. Imagine that you are currently working in an IT company and have been given a list of employees. You are asked by your manager to use Python to store this data for further company use.

This activity aims to help you use nested lists to store data and print them as you need them.

The data provided to you by your company is shown in Figure 2.5:

Figure 2.5 – Table consisting of employee data

Figure 2.5 – Table consisting of employee data

Follow these steps to complete this activity:

  1. Open a new Jupyter Notebook.
  2. Create a list and assign it to employees.
  3. Create three nested lists in employees to store the information of each employee, respectively.
  4. Print the employees variable.
  5. Print the details of all employees in a presentable format.
  6. Print only the details of Lisa Crawford.

By printing the details in a presentable format, the output will be as follows:

Figure 2.6 – Printed details of an employee using lists

Figure 2.6 – Printed details of an employee using lists

Note

The solution for this activity can be found in Appendix on GitHub.

In the next section, you will learn more about matrices and their operations.

You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022 Publisher: Packt ISBN-13: 9781804610619
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}