Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
The Python Workshop Second Edition

You're reading from   The Python Workshop Second Edition Write Python code to solve challenging real-world problems

Arrow left icon
Product type Paperback
Published in Nov 2022
Publisher Packt
ISBN-13 9781804610619
Length 600 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Mario Corchero Jiménez Mario Corchero Jiménez
Author Profile Icon Mario Corchero Jiménez
Mario Corchero Jiménez
Andrew Bird Andrew Bird
Author Profile Icon Andrew Bird
Andrew Bird
Corey Wade Corey Wade
Author Profile Icon Corey Wade
Corey Wade
Graham Lee Graham Lee
Author Profile Icon Graham Lee
Graham Lee
Dr. Lau Cher Han Dr. Lau Cher Han
Author Profile Icon Dr. Lau Cher Han
Dr. Lau Cher Han
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Chapter 1: Python Fundamentals – Math, Strings, Conditionals, and Loops 2. Chapter 2: Python Data Structures FREE CHAPTER 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

Tuples

A tuple object is similar to a list, but it cannot be changed. Tuples are immutable sequences, which means their values cannot be changed after initialization. You can use a tuple to represent fixed collections of items:

Figure 2.17 – A representation of a Python tuple with a positive index

Figure 2.17 – A representation of a Python tuple with a positive index

For instance, you can define the weekdays using a list, as follows:

weekdays_list = ['Monday', 'Tuesday', 'Wednesday', 
  'Thursday','Friday','Saturday', 'Sunday']

However, this does not guarantee that the values will remain unchanged throughout their life because a list is mutable. What you can do is define it using a tuple, as shown in the following code:

weekdays_tuple = ('Monday', 'Tuesday', 'Wednesday', 
  'Thursday','Friday','Saturday', 'Sunday')

As tuples are immutable, you can be certain that the values are consistent throughout the entire program and will not be modified accidentally or unintentionally. In the next exercise, you will explore the different properties tuples provide a Python developer.

Exercise 31 – exploring tuple properties in a dance genre list

In this exercise, you will learn about the different properties of a tuple:

  1. Open a Jupyter notebook.
  2. Type the following code in a new cell to initialize a new tuple, t:
    t = ('ballet', 'modern', 'hip-hop')
    print(len(t))

The output is as follows:

3

Note

Remember, a tuple is immutable; therefore, you can’t use the append method to add a new item to an existing tuple. You can’t change the value of any existing tuple’s elements since both of the following statements will raise an error.

  1. Now, as mentioned in the note, enter the following lines of code and observe the error:
    t[2] = 'jazz'

The output is as follows:

Figure 2.18 – Errors occur when we try to modify the values of a tuple object

Figure 2.18 – Errors occur when we try to modify the values of a tuple object

The only way to get around this is to create a new tuple by concatenating the existing tuple with other new items.

  1. Now, use the following code to add two items, jazz and tap, to our tuple, t. This will give us a new tuple. Note that the existing t tuple remains unchanged:
    print(t + ('jazz', 'tap'))
    print(t)

The output is as follows:

('ballet', 'modern', 'hip-hop', 'jazz', 'tap')
('ballet', 'modern', 'hip-hop')
  1. Enter the following statements in a new cell and observe the output:
    t_mixed = 'jazz', True, 3
    print(t_mixed)
    t_dance = ('jazz',3), ('ballroom',2), 
      ('contemporary',5)
    print(t_dance)

Tuples also support mixed types and nesting, just like lists and dictionaries. You can also declare a tuple without using parentheses, as shown in the code you entered in this step.

The output is as follows:

('jazz', True, 3)
(('jazz', 3), ('ballroom', 2), ('contemporary', 5))

Zipping and unzipping dictionaries and lists using zip()

Sometimes, you obtain information from multiple lists. For instance, you might have a list to store the names of products and another list just to store the quantity of those products. You can aggregate these lists using the zip() method.

The zip() method maps a similar index of multiple containers so that they can be used as a single object. You will try this out in the following exercise.

Exercise 32 – using the zip() method to manipulate dictionaries

In this exercise, you will work on the concept of dictionaries by combining different types of data structures. You will use the zip() method to manipulate the dictionary with our shopping list. The following steps will help you understand the zip() method:

  1. Open a new Jupyter Notebook.
  2. Now, create a new cell and type in the following code:
    items = ['apple', 'orange', 'banana']
    quantity = [5,3,2]

Here, you have created a list of items and a list of quantity. Also, you have assigned values to these lists.

  1. Now, use the zip() function to combine the two lists into a list of tuples:
    orders = zip(items,quantity)
    print(orders)

This gives us a zip() object with the following output:

<zip object at 0x0000000005BF1088>
  1. Enter the following code to turn that zip() object into a list:
    orders = zip(items,quantity)
    print(list(orders))

The output is as follows:

[('apple', 5), ('orange', 3), ('banana', 2)]
  1. You can also turn a zip() object into a tuple:
    orders = zip(items,quantity)
    print(tuple(orders))

Let’s see the output:

(('apple', 5), ('orange', 3), ('banana', 2))
  1. You can also turn a zip() object into a dictionary:
    orders = zip(items,quantity)
    print(dict(orders))

Let’s see the output:

{'apple': 5, 'orange': 3, 'banana': 2}

Did you realize that you have to call orders = zip(items,quantity) every time? In this exercise, you will have noticed that a zip() object is an iterator, so once it has been converted into a list, tuple, or dictionary, it is considered a full iteration and it will not be able to generate any more values.

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 $19.99/month. Cancel anytime
Banner background image