Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
The Python Workshop
The Python Workshop

The Python Workshop: Learn to code in Python and kickstart your career in software development or data science

Arrow left icon
Profile Icon Pons Profile Icon Bird Profile Icon Lee Profile Icon Dr. Lau Cher Han Profile Icon Mario Corchero Jiménez Profile Icon Wade +2 more Show less
Arrow right icon
$34.98 $49.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (36 Ratings)
eBook Nov 2019 608 pages 1st Edition
eBook
$34.98 $49.99
Paperback
$62.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Pons Profile Icon Bird Profile Icon Lee Profile Icon Dr. Lau Cher Han Profile Icon Mario Corchero Jiménez Profile Icon Wade +2 more Show less
Arrow right icon
$34.98 $49.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3 (36 Ratings)
eBook Nov 2019 608 pages 1st Edition
eBook
$34.98 $49.99
Paperback
$62.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$34.98 $49.99
Paperback
$62.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

The Python Workshop

2. Python Structures

Overview

By the end of this chapter, you will be able to explain the different types of Python data structures; create lists, dictionaries, and sets and describe the differences between them; create matrices and manipulate both a matrix as a whole and its individual cells; call the zip() function to create different Python structures; find what methods are available for lists, dictionaries, and sets; write a program using the most popular methods for lists, dictionaries, and sets and convert between different Python structures.

Introduction

In the previous chapter, you learned the basics of the Python programming language and essential elements such as string, int, and the use of conditionals and loops that control the flow of a Python program. You should now be familiar with writing programs in Python by utilizing these elements.

In this chapter, you are going to look at how to use data structures to store more complex types of data that help to model the actual data and represent it in the real world.

In programming languages, data structures refer to objects that can hold some data together, which means they are used to store a collection of related data.

For instance, you can use a list to store our to-do items for the day. The following is an example to show you how lists are coded:

todo = ["pick up laundry", "buy Groceries", "pay electric bills"]

We can also use a dictionary object to store more complex information such as subscribers' details...

The Power of Lists

You will now look at the first type of data structure in Python: lists.

A list is a type of container in Python that is used to store multiple data sets at the same time. Python lists are often compared to arrays in other programming languages, but they do a lot more.

Figure 2.2: A Python list with a positive index

A list in Python is written within square brackets, [ ]. Each element in the list has its own distinct position and index. The elements in a list have a finite sequence. Like other programming languages, the index of the first item of a list is 0, and the second item has an index of 1, and so on. This has to do with how lists are implemented at a lower programming level, so do take note of this when you are writing index-based operations for lists and other iterable objects.

You will now look at the different ways that lists can be useful by completing Exercise 21, Working with Python Lists.

Exercise 21: Working with...

Matrix Operations

You will continue to look at how to use nested lists for some basic matrix operations. First, you look at how to add two matrices in Python. Matrix addition requires both matrices to have the same dimensions; the results will also be of the same dimensions.

In Exercise 23, Implementing Matrix Operations (Addition and Subtraction), you will be using the following matrix data, X and Y, in figures 2.7 and 2.8:

Figure 2.7: Matrix data for matrix X

Figure 2.8: Matrix data for matrix Y

Exercise 23: Implementing Matrix Operations (Addition and Subtraction)

In this exercise you will add and subtract the X and Y matrixes using Python.

The following steps will enable you to complete the exercise:

  1. Open a new Jupyter Notebook.
  2. Create two nested lists, X and Y, to store the values:
    X = [[1,2,3],[4,5,6],[7,8,9]]
    Y = [[10,11,12],[13,14,15],[16,17,18]]
  3. Initialize a 3 x 3 zero matrix called result as a placeholder...

List Methods

As discussed before, 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 in order to maintain, update, and extract data. These common operations are what Python programmers perform, including slicing, sorting, appending, searching, inserting, and removing data.

The best way to understand this is to see them at work. You will learn about these handy list methods in the following exercises.

Exercise 25: Basic List Operations

In this exercise, you are going to use the basic functions of lists to check the size of a list, combining lists and duplicating lists as well. Follow these steps:

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

Dictionary Keys and Values

A Python dictionary is an unordered collection. Dictionaries are written with curly brackets, and they have keys and values.

For instance, have a look at the following example, where you store the details of an employee:

employee = {
  'name': "Jack Nelson",
  'age': 32,
  'department': "sales"
}

You might have noticed a certain resemblance between Python dictionaries and JSON. Although you can load JSON directly into Python, a Python dictionary is a complete data structure that implements its own algorithms, and JSON is just a pure string written in a similar format..

Python dictionaries are something similar to key-value pairs. They simply map keys to associated values, as shown in Figure 2.12:

Figure 2.12: Mapping keys and values in Python dictionaries

Dictionaries are like lists. They both share the following properties:

  • Both can...

Dictionary Methods

Now that you have learned about dictionaries and when you should use a dictionary. You will now look at a few other dictionary methods. To start with, you should follow the exercises from here onward to learn how to access the values and other related operations of a dictionary in Python.

Exercise 30: Accessing a Dictionary Using Dictionary Methods

In this exercise, we will learn how to access a dictionary using dictionary methods. The goal of the exercise is to print the order values against the item while accessing the dictionary by using dictionary methods:

  1. Open a new Jupyter Notebook.
  2. Enter the following code in a new cell:
    orders = {'apple':5, 'orange':3, 'banana':2}
    print(orders.values())
    print(list(orders.values()))

    You should get the following output:

    dict_values([5, 3, 2])
    [5, 3, 2]

    The values() method in this code returns an iterable object. In order to use the values straight away, you can wrap them in a list...

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 use a tuple to represent fixed collections of items:

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 its lifetime because a list is mutable. What we can do is to 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...

A Survey of Sets

So far, in this chapter, you have covered lists, dictionaries, and tuples. You can now have a look at sets, which are another type of Python data structure.

Sets are a relatively new addition to the Python collection type. They are unordered collections of unique and immutable objects that support operations mimicking mathematical set theory. As sets do not allow multiple occurrences of the same element, they can be used to effectively prevent duplicate values.

A set is a collection of objects (called members or elements). For instance, you can define set A as even numbers between 1 to 10, and it will contain {2,4,6,8,10}, and set B can be odd numbers between 1 to 10, and it will contain {1,3,5,7,9}. In the following exercise, you will get our hands on sets in Python:

Figure 2.21: Set A and Set B – each set contains a unique, distinct value

Exercise 32: Using Sets in Python

In this exercise, you will gain an understanding...

Choosing Types

By now, you have learned about most of the common data structures in Python. One of the challenges you might face is knowing when to use the various data types.

When choosing a collection type, it is useful to understand the unique properties of that type. For example, a list is for you to store multiple objects and to retain a sequence, a dictionary is for us to store unique key-value pair mappings, tuples are immutable, and sets only store unique elements. Choosing the right type for a particular dataset could mean an increase in efficiency or security.

Choosing an incorrect type for your data will lead to data loss, in most cases it leads to low efficiency while running our code, and in the worst case, we might lose our data.

Summary

To summarize, you need to remember that Python data structures include lists, tuples, dictionaries, and sets. Python provides these structures to enable you to code better as a developer. In this chapter, you have covered lists, which are one of the important data types in Python that store multiple objects, and also other data types, such as dictionaries, tuples, and sets. Each of these data types helps us to store and retrieve data effectively.

Data structures are an essential part of all programming languages. Most programming languages only provide basic data types to store different types of numbers, strings, and Booleans, as you learned in Chapter 1, Vital Python - Math, Strings, Conditionals, and Loops. They are an essential part of any program. In this chapter, you learned how to utilize advanced data structures such as nested lists and mixed data types, and lists with dictionaries — structures that you can use to store complex data.

Next up, we are going...

Left arrow icon Right arrow icon

Key benefits

  • Build key Python skills with engaging development tasks and challenging activities
  • Implement useful algorithms and write programs to solve real-world problems
  • Apply Python in realistic data science projects and create simple machine learning models

Description

Have you always wanted to learn Python, but never quite known how to start? More applications than we realize are being developed using Python because it is easy to learn, read, and write. You can now start learning the language quickly and effectively with the help of this interactive tutorial. The Python Workshop starts by showing you how to correctly apply Python syntax to write simple programs, and how to use appropriate Python structures to store and retrieve data. You'll see how to handle files, deal with errors, and use classes and methods to write concise, reusable, and efficient code. As you advance, you'll understand how to use the standard library, debug code to troubleshoot problems, and write unit tests to validate application behavior. You'll gain insights into using the pandas and NumPy libraries for analyzing data, and the graphical libraries of Matplotlib and Seaborn to create impactful data visualizations. By focusing on entry-level data science, you'll build your practical Python skills in a way that mirrors real-world development. Finally, you'll discover the key steps in building and using simple machine learning algorithms. By the end of this Python book, you'll have the knowledge, skills and confidence to creatively tackle your own ambitious projects with Python.

Who is this book for?

This book is designed for anyone who is new to the Python programming language. Whether you're an aspiring software engineer or data scientist, or are just curious about learning how to code with Python, this book is for you. No prior programming experience is required.

What you will learn

  • Write clean and well-commented code that is easy to maintain
  • Automate essential day-to-day tasks with Python scripts
  • Debug logical errors and handle exceptions in your programs
  • Explore data science fundamentals and create engaging visualizations
  • Get started with predictive machine learning
  • Keep your development process bug-free with automated testing

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 06, 2019
Length: 608 pages
Edition : 1st
Language : English
ISBN-13 : 9781838984533
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Nov 06, 2019
Length: 608 pages
Edition : 1st
Language : English
ISBN-13 : 9781838984533
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 156.97
The Python Workshop
$62.99
The JavaScript Workshop
$43.99
40 Algorithms Every Programmer Should Know
$49.99
Total $ 156.97 Stars icon

Table of Contents

11 Chapters
1. Vital Python – Math, Strings, Conditionals, and Loops Chevron down icon Chevron up icon
2. Python Structures Chevron down icon Chevron up icon
3. Executing Python – Programs, Algorithms, and Functions Chevron down icon Chevron up icon
4. Extending Python, Files, Errors, and Graphs Chevron down icon Chevron up icon
5. Constructing Python – Classes and Methods Chevron down icon Chevron up icon
6. The Standard Library Chevron down icon Chevron up icon
7. Becoming Pythonic Chevron down icon Chevron up icon
8. Software Development Chevron down icon Chevron up icon
9. Practical Python – Advanced Topics Chevron down icon Chevron up icon
10. Data Analytics with pandas and NumPy Chevron down icon Chevron up icon
11. Machine Learning Chevron down icon Chevron up icon

Customer reviews

Most Recent
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(36 Ratings)
5 star 66.7%
4 star 16.7%
3 star 5.6%
2 star 0%
1 star 11.1%
Filter icon Filter
Most Recent

Filter reviews by




road_warrior May 23, 2023
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Book logically presents python syntax examples and has answers in back. Explains examples fairly well. Expecting more structured modular coding emphasis though.
Amazon Verified review Amazon
Michael Whitney Jan 06, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Examples are a great way to learn so this is perfect way to begin to learn Python. Very easy to follow
Amazon Verified review Amazon
None Oct 14, 2021
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I purchased the book from Amazon several months ago. This the print version. I didn't immediately start reading it because I was working other on projects. I picked up the book today and realized it is missing pages. Obviously there is no quality control. Very disappointed.
Amazon Verified review Amazon
ShivamPandey Mar 21, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
"The Python Workshop" gives an comprehensive, advanced language features, an in-depth introduction to the core Python language with this hands-on book. It will help you quickly write efficient, high-quality code with Python. It’s an ideal way to begin, regardless of whether you’re new to programming or a professional developer versed in other languages.This is a great, thorough, quality book on Python, targeted at individuals who have some experience writing programs, but who want to learn Python to write production-grade Python programs.The entirety of the Python ecosystem is MASSIVE, and this book goes into detail about a lot of that ecosystem.(Although even a book of this size does not cover ALL of that ecosystem).This includes things like: Python Structure,Algorithms & Functions, Software Development, Data Sciences/Analytics, Machine Learning, Classes & Methods etc.You'll see how to handle files, deal with errors, and use classes and methods to write concise, reusable, and efficient code.Performing hands on Jupyter along with reading each chapter is the most efficient manner of learning from this book. Appendix & Index is an good aid while reading the book. This book effectively provides to use a programming language, there is a lot to learn. And this book does a great job of metering out that information.I would recommend this book for Python enthusiasts. It's great book to be used as a reference resource in schools narrowing on use of Python. Shout out for 'Packt Publication' for being the publication partner on this book.
Amazon Verified review Amazon
Art Feb 24, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Bought a copy for my Grandson who is learning computers and their programming, le likes it too,
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.