Reader small image

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

Product typeBook
Published inNov 2022
Reading LevelN/a
PublisherPackt
ISBN-139781804610619
Edition2nd Edition
Languages
Right arrow
Authors (5):
Corey Wade
Corey Wade
author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

Mario Corchero Jiménez
Mario Corchero Jiménez
author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Dr. Lau Cher Han
Dr. Lau Cher Han
author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

Graham Lee
Graham Lee
author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee

View More author details
Right arrow

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.

Previous PageNext Page
You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022Publisher: PacktISBN-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.
undefined
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 $15.99/month. Cancel anytime

Authors (5)

author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee