Best Python books

| | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Best book to learn Python

In this article, we highlight the best books for learning Python through a collection of book reviews. Each review offers a taste of the book, the topics covered and the context used to illustrate those topics. Different books will resonate with different people, depending on the style and presentation of the books, reader backgrounds, and other factors.

Python is an amazing programming language. It can be applied to almost any programming task, allows for rapid development and debugging, and offers support from what is arguably the friendliest user community.

Best Python book for Beginners

Getting started with Python is like learning a new skill - it’s important to find a resource that you can connect with to guide your learning. Fortunately, there is no shortage of excellent books that can help you learn both the basics of programming and the specifics of programming in Python. With an abundance of resources, it can be difficult to identify which book would be best for your situation.

If you are new to Python, one of the introductory books will give you a solid foundation.

Maybe you want to learn Python with your kid, or maybe you want to teach Python to a group of kids. Check out the best Python children’s books for resources aimed at a younger audience.

As you progress through your Python journey, you’ll want to dig deeper to maximize the efficiency of your code. The best intermediate and advanced Python books provide information to help you improve your Python skills, thus enabling you to become a Python expert.

Best Python book for Programmers

After reading these reviews, if you’re still not sure which book to choose, publishers often provide a sample chapter or section to give you an example of what the book has to offer. Reading a sample of the book should give you the most representative picture of the author’s pace, style, and expectations.

Whichever book stands out the most, consider this anecdote from one of our book reviewers, Steven C. Howell:

"A favorite teacher once said to me, ’It doesn’t matter which book you read first. It’s always the second that makes the most sense. "

I can’t say it has always been that way for me, but I have certainly found that a second referral can make all the difference when the first has left me confused or frustrated.

While learning the Python lessons, I had a hard time understanding the examples used in the first two books I collected. It wasn’t until the third book I referred to that the concepts started to click.

The important lesson is that if you’re stuck or frustrated and the resources you have aren’t helping you, don’t give up. Look at another book, search the web, ask questions on a forum, or just take a break. "

Note: This article contains affiliate links to retailers such as Amazon, so you can support Real Python by clicking and making a purchase on some of the links. There is no additional cost to you to purchase from any of these links. Affiliate links do not influence our editorial decisions in any way.

The best books to learn Python

If you’re new to Python, you probably find yourself in one of two situations:

You are new to programming and want to start learning Python. You have good experience programming in another language and now want to learn Python. This section focuses on the first of these two scenarios, with reviews of books that we consider to be the best Python programming books for readers new to programming and Python. Therefore, these books do not require any previous programming experience. They start with the absolute basics and teach both general programming concepts and their application to Python.

Python crash course

Eric Matthes (No Starch Press, 2016)

It does what he says on the box, and it does it very well. The book begins with an overview of the basic elements and data structures of Python, using variables, strings, numbers, lists and tuples, describing how you work with each of them.

So, if the instructions and logical tests are covered, followed by a dip in the dictionaries. Next, the book covers user input, loops, functions, classes, and file management, as well as testing and debugging code.

This is only the first half of the book! In the second half, you work on three main projects, creating smart and fun apps.

The first project is an Alien Invasion game, essentially Space Invaders, developed using the pygame package. You design a ship (using classes), then plan how to fly it and make it fire bullets. So you design different classes of aliens, move the alien fleet and allow them to be shot down. Finally, add a scoreboard and a high score list to complete the game.

Next, the next project covers data visualization with matplotlib, random walks, dice rolling and some statistical analysis, creating graphs and tables with the pygal package. You learn how to download data in various formats, import it into Python and view the results, as well as interact with web APIs, retrieve and view data from GitHub and HackerNews.

The third project walks you through creating a complete web application that uses Django to create a learning diary to keep track of what users have studied. It explains how to install Django, configure a project, design your own templates, create an admin interface, configure user accounts, manage user access controls per user, model the entire application with Bootstrap, and finally deploy it to Heroku. .

This book is well written and well organized. It features a large number of useful exercises and three challenging and fun projects that make up the second half of the book. (Comment by David Schlesinger.)

Head-First Python, 2nd edition

I really like the Head-First series of books, although their overall content is certainly lighter than most of the other recommendations in this section. The trade-off is that this approach makes the book more user-friendly.

If you’re the kind of person who likes to learn things a little at a time and you want to have lots of real-life examples and illustrations of the concepts involved, then the Head-First series is for you. The publisher’s website has the following to say about their approach:

"Based on the latest research in cognitive science and learning theory, Head-First Python uses a visually rich format to engage your mind, rather than a text-rich approach that puts you to sleep. Why waste time struggling with new concepts? This multisensory learning experience is designed for the actual functioning of your brain. (Source)

Packed with illustrations, examples, parentheses and other information, Head-First Python is always engaging and easy to read. This book begins its Python tour by delving into the lists and explaining how to use and manipulate them. So it goes into modules, errors and file handling. Each theme is organized around a unifying project: building a dynamic website for a school sports coach using Python via a Common Gateway Interface (CGI).

Next, the book spends some time teaching you how to use an Android app to interact with the website you created. You will learn how to handle user input, encode data, and explore the implications of deploying and scaling a Python application on the web.

While this book isn’t as comprehensive as some of the others, it covers a good range of Python tasks in a way that is arguably more accessible, painless, and efficient. This is especially true if you find the topic of writing programs a little intimidating at first.

This book is designed to guide you through any challenge. While the content is more targeted, there is plenty of material to keep you busy and learn. You won’t be bored. If you find that most of the program books

Think Python: How to Think Like a Computer Scientist, 2nd Edition

If learning Python while making video games is too frivolous for you, consider Allen Downey’s book Think Python, which takes a much more serious approach.

As the title suggests, the purpose of this book is to teach you how programmers think about programming, and it does a good job. Compared to other books, it is drier and organized in a more linear fashion. The book focuses on everything you need to know about basic programming in Python, in a very simple, clear, and comprehensive way.

Compared to other similar books, it doesn’t go as far in some of the more advanced areas, but rather covers a wider range of material, including topics that other books don’t come close to. Examples of such topics include operator overload, polymorphism, algorithm analysis, and mutability versus immutability.

The previous versions were a bit light on the exercises, but the latest edition has largely corrected this shortcoming. There are four reasonably in-depth projects in the book, presented as case studies, but overall it has fewer exercises of direct application than many other books.

If you like a step-by-step presentation of the facts and want to get a better idea of ‚Äã‚Äãhow professional programmers view problems, this book is a great choice. (Reviewed by David Schlesinger and Steven C. Howell.)

Efficient Computing in Physics: A Field Guide for Research with Python

This is the book I wish I had had when I was first learning Python.

Despite the name, this book is a great choice for people who have no background in physics, research, or computer problems.

It really is a hands-on guide to using Python. Besides teaching you Python, it also covers related topics, such as command line and version control, as well as software testing and distribution.

As well as being a great learning resource, this book will also serve as a great reference for Python, as the topics are well organized with lots of examples and exercises intertwined.

The book is divided into four aptly named sections: How To Start, How To Do It, How To Do It Right, and How To Get It Out.

The Getting Started section contains everything you need to start running. Start with a chapter on bash command line fundamentals. (Yes, you can even install bash for Windows.) The book then explains the basics of Python, covering all expected topics: operators, strings, variables, containers, logic, and flow control. In addition, there is an entire chapter devoted to all the different types of functions, and another to classes and object-oriented programming.

Building on that foundation, the How To section moves to the more data-centric area of ‚Äã‚ÄãPython. Note that this section, which takes up about a third of the book, will be more applicable to scientists, engineers, and data scientists. If that’s you, have fun. If not, feel free to continue by selecting the relevant sections. But be sure to read the last chapter of the section as it will teach you how to deploy software using pip, conda, virtual machines, and Docker containers.

For those of you who want to work with data, the section begins with a brief overview of essential libraries for analyzing and visualizing data. You then have a separate chapter dedicated to teaching you the topics of regular expressions, NumPy, data storage (including performing operations out of the core), specialized data structures (hash tables, data, D trees and kd trees), and parallel computation.

The Getting It Right section teaches you how to avoid and overcome many of the common pitfalls associated with working in Python. Start by expanding the discussion of software distribution by teaching you how to create software pipelines using make. You will then learn how to use Git and GitHub to track, archive, and organize code changes over time - a process called version control. The section ends by teaching you how to debug and test your code, two incredibly valuable skills.

Learn Python 3 the hard way

Learning Python the hard way is a classic. I’m a big fan of the book’s approach. When you learn "the hard way" you should:

The positive aspect of this book is the quality of the presentation of the contents. Each chapter is presented clearly. The code examples are all concise, well constructed, and straight to the point. The exercises are informative and the problems you will encounter will not be overwhelming at all. Your biggest risk is typographical errors. Read this book and you will surely no longer be a beginner in Python.

Don’t be put off by the title. The "hard way" turns out to be the easiest way if you are looking for the long haul. Nobody likes to write a lot, but that’s what programming entails, so it’s good to get used to it from the start. One good thing about this book is that it has been perfected through several editions now, so all the edges have been made nice and smooth now.

The book is built as a series of over fifty exercises, each based on the previous one and each teaching you a new characteristic of the language. From Exercise 0, by installing Python on your computer, you start writing simple programs. You will learn about variables, data types, functions, logic, loops, lists, debugging, dictionaries, object-oriented programming, inheritance, and packaging. You can even create a simple game using a game engine.

The following sections cover concepts such as automated testing, lexical user input analysis to parse sentences, and the lpthw.web package, to bring your game to the web.

Zed is an engaging and patient writer who doesn’t hide the details. If you work on this book the right way - the "hard way" by following the study tips provided throughout the text and programming exercises - you will be well beyond the beginner programmer stage when you are done. (Comment by David Schlesinger.)

Real Python course part 1

This eBook is the first of three (so far) in the Real Python course series. It was written with the goal of getting started and does a great job of achieving that. The book is a mix of explanatory prose, sample code, and revision exercises. Interval Revision Exercises solidify your learning by allowing you to immediately apply what you have learned.

As with the previous books, clear instructions are provided for installing and running Python on your computer. After the configuration section, instead of providing a brief summary of the data types, Real Python starts with strings and is actually pretty comprehensive - you learn how to split strings before you get to page 30.

So the book gives you a good idea of ‚Äã‚Äãthe flavor of Python by showing you how to play around with some of the class methods that can be applied. You then learn to write functions and loops, use conditional logic, work with lists and dictionaries, and read and write files.

Then things get really fun! Once you learn how to install packages with pip (and from source), Real Python covers interacting and manipulating PDFs, using SQL from Python, retrieving data from web pages, using numpy and matplotlib to perform scientific calculations and, finally, the creation of graphical user interfaces with EasyGUI and tkinter.

What I love most about Real Python is that in addition to covering the basics in an in-depth and intuitive way, the book explores more advanced uses of Python that none of the other books have covered, such as web scratching. There are also two additional volumes, dedicated to more advanced Python development.

👻 Read also: what is the best laptop for engineering students?

Best Python books __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Best Python books __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

5 answers

Carl Meyer By Carl Meyer

I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged (i.e. taking the union). The update() method would be what I need, if it returned its result instead of modifying a dictionary in-place.

>>> x = {"a": 1, "b": 2}
>>> y = {"b": 10, "c": 11}
>>> z = x.update(y)
>>> print(z)
None
>>> x
{"a": 1, "b": 10, "c": 11}

How can I get that final merged dictionary in z, not x?

(To be extra-clear, the last-one-wins conflict-handling of dict.update() is what I"m looking for as well.)

5839

Answer #1

How can I merge two Python dictionaries in a single expression?

For dictionaries x and y, z becomes a shallowly-merged dictionary with values from y replacing those from x.

  • In Python 3.9.0 or greater (released 17 October 2020): PEP-584, discussed here, was implemented and provides the simplest method:

    z = x | y          # NOTE: 3.9+ ONLY
    
  • In Python 3.5 or greater:

    z = {**x, **y}
    
  • In Python 2, (or 3.4 or lower) write a function:

    def merge_two_dicts(x, y):
        z = x.copy()   # start with keys and values of x
        z.update(y)    # modifies z with keys and values of y
        return z
    

    and now:

    z = merge_two_dicts(x, y)
    

Explanation

Say you have two dictionaries and you want to merge them into a new dictionary without altering the original dictionaries:

x = {"a": 1, "b": 2}
y = {"b": 3, "c": 4}

The desired result is to get a new dictionary (z) with the values merged, and the second dictionary"s values overwriting those from the first.

>>> z
{"a": 1, "b": 3, "c": 4}

A new syntax for this, proposed in PEP 448 and available as of Python 3.5, is

z = {**x, **y}

And it is indeed a single expression.

Note that we can merge in with literal notation as well:

z = {**x, "foo": 1, "bar": 2, **y}

and now:

>>> z
{"a": 1, "b": 3, "foo": 1, "bar": 2, "c": 4}

It is now showing as implemented in the release schedule for 3.5, PEP 478, and it has now made its way into the What"s New in Python 3.5 document.

However, since many organizations are still on Python 2, you may wish to do this in a backward-compatible way. The classically Pythonic way, available in Python 2 and Python 3.0-3.4, is to do this as a two-step process:

z = x.copy()
z.update(y) # which returns None since it mutates z

In both approaches, y will come second and its values will replace x"s values, thus b will point to 3 in our final result.

Not yet on Python 3.5, but want a single expression

If you are not yet on Python 3.5 or need to write backward-compatible code, and you want this in a single expression, the most performant while the correct approach is to put it in a function:

def merge_two_dicts(x, y):
    """Given two dictionaries, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z

and then you have a single expression:

z = merge_two_dicts(x, y)

You can also make a function to merge an arbitrary number of dictionaries, from zero to a very large number:

def merge_dicts(*dict_args):
    """
    Given any number of dictionaries, shallow copy and merge into a new dict,
    precedence goes to key-value pairs in latter dictionaries.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

This function will work in Python 2 and 3 for all dictionaries. e.g. given dictionaries a to g:

z = merge_dicts(a, b, c, d, e, f, g) 

and key-value pairs in g will take precedence over dictionaries a to f, and so on.

Critiques of Other Answers

Don"t use what you see in the formerly accepted answer:

z = dict(x.items() + y.items())

In Python 2, you create two lists in memory for each dict, create a third list in memory with length equal to the length of the first two put together, and then discard all three lists to create the dict. In Python 3, this will fail because you"re adding two dict_items objects together, not two lists -

>>> c = dict(a.items() + b.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: "dict_items" and "dict_items"

and you would have to explicitly create them as lists, e.g. z = dict(list(x.items()) + list(y.items())). This is a waste of resources and computation power.

Similarly, taking the union of items() in Python 3 (viewitems() in Python 2.7) will also fail when values are unhashable objects (like lists, for example). Even if your values are hashable, since sets are semantically unordered, the behavior is undefined in regards to precedence. So don"t do this:

>>> c = dict(a.items() | b.items())

This example demonstrates what happens when values are unhashable:

>>> x = {"a": []}
>>> y = {"b": []}
>>> dict(x.items() | y.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: "list"

Here"s an example where y should have precedence, but instead the value from x is retained due to the arbitrary order of sets:

>>> x = {"a": 2}
>>> y = {"a": 1}
>>> dict(x.items() | y.items())
{"a": 2}

Another hack you should not use:

z = dict(x, **y)

This uses the dict constructor and is very fast and memory-efficient (even slightly more so than our two-step process) but unless you know precisely what is happening here (that is, the second dict is being passed as keyword arguments to the dict constructor), it"s difficult to read, it"s not the intended usage, and so it is not Pythonic.

Here"s an example of the usage being remediated in django.

Dictionaries are intended to take hashable keys (e.g. frozensets or tuples), but this method fails in Python 3 when keys are not strings.

>>> c = dict(a, **b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: keyword arguments must be strings

From the mailing list, Guido van Rossum, the creator of the language, wrote:

I am fine with declaring dict({}, **{1:3}) illegal, since after all it is abuse of the ** mechanism.

and

Apparently dict(x, **y) is going around as "cool hack" for "call x.update(y) and return x". Personally, I find it more despicable than cool.

It is my understanding (as well as the understanding of the creator of the language) that the intended usage for dict(**y) is for creating dictionaries for readability purposes, e.g.:

dict(a=1, b=10, c=11)

instead of

{"a": 1, "b": 10, "c": 11}

Response to comments

Despite what Guido says, dict(x, **y) is in line with the dict specification, which btw. works for both Python 2 and 3. The fact that this only works for string keys is a direct consequence of how keyword parameters work and not a short-coming of dict. Nor is using the ** operator in this place an abuse of the mechanism, in fact, ** was designed precisely to pass dictionaries as keywords.

Again, it doesn"t work for 3 when keys are not strings. The implicit calling contract is that namespaces take ordinary dictionaries, while users must only pass keyword arguments that are strings. All other callables enforced it. dict broke this consistency in Python 2:

>>> foo(**{("a", "b"): None})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() keywords must be strings
>>> dict(**{("a", "b"): None})
{("a", "b"): None}

This inconsistency was bad given other implementations of Python (PyPy, Jython, IronPython). Thus it was fixed in Python 3, as this usage could be a breaking change.

I submit to you that it is malicious incompetence to intentionally write code that only works in one version of a language or that only works given certain arbitrary constraints.

More comments:

dict(x.items() + y.items()) is still the most readable solution for Python 2. Readability counts.

My response: merge_two_dicts(x, y) actually seems much clearer to me, if we"re actually concerned about readability. And it is not forward compatible, as Python 2 is increasingly deprecated.

{**x, **y} does not seem to handle nested dictionaries. the contents of nested keys are simply overwritten, not merged [...] I ended up being burnt by these answers that do not merge recursively and I was surprised no one mentioned it. In my interpretation of the word "merging" these answers describe "updating one dict with another", and not merging.

Yes. I must refer you back to the question, which is asking for a shallow merge of two dictionaries, with the first"s values being overwritten by the second"s - in a single expression.

Assuming two dictionaries of dictionaries, one might recursively merge them in a single function, but you should be careful not to modify the dictionaries from either source, and the surest way to avoid that is to make a copy when assigning values. As keys must be hashable and are usually therefore immutable, it is pointless to copy them:

from copy import deepcopy

def dict_of_dicts_merge(x, y):
    z = {}
    overlapping_keys = x.keys() & y.keys()
    for key in overlapping_keys:
        z[key] = dict_of_dicts_merge(x[key], y[key])
    for key in x.keys() - overlapping_keys:
        z[key] = deepcopy(x[key])
    for key in y.keys() - overlapping_keys:
        z[key] = deepcopy(y[key])
    return z

Usage:

>>> x = {"a":{1:{}}, "b": {2:{}}}
>>> y = {"b":{10:{}}, "c": {11:{}}}
>>> dict_of_dicts_merge(x, y)
{"b": {2: {}, 10: {}}, "a": {1: {}}, "c": {11: {}}}

Coming up with contingencies for other value types is far beyond the scope of this question, so I will point you at my answer to the canonical question on a "Dictionaries of dictionaries merge".

Less Performant But Correct Ad-hocs

These approaches are less performant, but they will provide correct behavior. They will be much less performant than copy and update or the new unpacking because they iterate through each key-value pair at a higher level of abstraction, but they do respect the order of precedence (latter dictionaries have precedence)

You can also chain the dictionaries manually inside a dict comprehension:

{k: v for d in dicts for k, v in d.items()} # iteritems in Python 2.7

or in Python 2.6 (and perhaps as early as 2.4 when generator expressions were introduced):

dict((k, v) for d in dicts for k, v in d.items()) # iteritems in Python 2

itertools.chain will chain the iterators over the key-value pairs in the correct order:

from itertools import chain
z = dict(chain(x.items(), y.items())) # iteritems in Python 2

Performance Analysis

I"m only going to do the performance analysis of the usages known to behave correctly. (Self-contained so you can copy and paste yourself.)

from timeit import repeat
from itertools import chain

x = dict.fromkeys("abcdefg")
y = dict.fromkeys("efghijk")

def merge_two_dicts(x, y):
    z = x.copy()
    z.update(y)
    return z

min(repeat(lambda: {**x, **y}))
min(repeat(lambda: merge_two_dicts(x, y)))
min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
min(repeat(lambda: dict(chain(x.items(), y.items()))))
min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))

In Python 3.8.1, NixOS:

>>> min(repeat(lambda: {**x, **y}))
1.0804965235292912
>>> min(repeat(lambda: merge_two_dicts(x, y)))
1.636518670246005
>>> min(repeat(lambda: {k: v for d in (x, y) for k, v in d.items()}))
3.1779992282390594
>>> min(repeat(lambda: dict(chain(x.items(), y.items()))))
2.740647904574871
>>> min(repeat(lambda: dict(item for d in (x, y) for item in d.items())))
4.266070580109954
$ uname -a
Linux nixos 4.19.113 #1-NixOS SMP Wed Mar 25 07:06:15 UTC 2020 x86_64 GNU/Linux

Resources on Dictionaries

5839

Answer #2

In your case, what you can do is:

z = dict(list(x.items()) + list(y.items()))

This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict"s value:

>>> x = {"a":1, "b": 2}
>>> y = {"b":10, "c": 11}
>>> z = dict(list(x.items()) + list(y.items()))
>>> z
{"a": 1, "c": 11, "b": 10}

If you use Python 2, you can even remove the list() calls. To create z:

>>> z = dict(x.items() + y.items())
>>> z
{"a": 1, "c": 11, "b": 10}

If you use Python version 3.9.0a4 or greater, then you can directly use:

x = {"a":1, "b": 2}
y = {"b":10, "c": 11}
z = x | y
print(z)
{"a": 1, "c": 11, "b": 10}

5839

Answer #3

An alternative:

z = x.copy()
z.update(y)

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method