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
Arrow up icon
GO TO TOP
Learn Python Programming

You're reading from   Learn Python Programming A comprehensive, up-to-date, and definitive guide to learning Python

Arrow left icon
Product type Paperback
Published in Nov 2024
Publisher Packt
ISBN-13 9781835882948
Length 616 pages
Edition 4th Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Heinrich Kruger Heinrich Kruger
Author Profile Icon Heinrich Kruger
Heinrich Kruger
Fabrizio Romano Fabrizio Romano
Author Profile Icon Fabrizio Romano
Fabrizio Romano
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface A Gentle Introduction to Python FREE CHAPTER Built-In Data Types Conditionals and Iteration Functions, the Building Blocks of Code Comprehensions and Generators OOP, Decorators, and Iterators Exceptions and Context Managers Files and Data Persistence Cryptography and Tokens Testing Debugging and Profiling Introduction to Type Hinting Data Science in Brief Introduction to API Development CLI Applications Packaging Python Applications Programming Challenges Other Books You May Enjoy
Index

Name localization

Now that we are familiar with all types of comprehensions and generator expressions, let us talk about name localization within them. Python 3 localizes loop variables in all four forms of comprehensions: list, dictionary, set, and generator expressions. This behavior is different from that of the for loop. Let us look at some simple examples to show all the cases:

# scopes.py
A = 100
ex1 = [A for A in range(5)]
print(A)  # prints: 100
ex2 = list(A for A in range(5))
print(A)  # prints: 100
ex3 = {A: 2 * A for A in range(5)}
print(A)  # prints: 100
ex4 = {A for A in range(5)}
print(A)  # prints: 100
s = 0
for A in range(5):
    s += A
print(A)  # prints: 4

In the preceding code, we declare a global name, A = 100. We then have list, dictionary, and set comprehensions, and a generator expression. Even though they all use the name A, none of them alter the global name, A. On the other hand, the for loop at the end does modify the global A. The last print statement...

lock icon The rest of the chapter is locked
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