21.7 C
New York
Saturday, August 2, 2025

How To Write Environment friendly Python Code: A Tutorial for Newcomers


 

How To Write Environment friendly Python Code: A Tutorial for Newcomers
Picture by Writer

 

Newbie programmers get pleasure from coding in Python due to its simplicity and easy-to-read syntax. Writing environment friendly Python code, nevertheless, is extra concerned than you suppose. It requires understanding of a number of the options of the language (they’re simply as easy to select up, although).

When you’re coming from one other programming language comparable to C++ or JavaScript, this tutorial is so that you can be taught some tricks to write environment friendly code in Python. However in case you are a newbie—studying Python as your first (programming) language—then this tutorial will assist you write Pythonic code from the get go.

We’ll give attention to the next:

 

  • Pythonic loops
  • Checklist and dictionary comprehension
  • Context managers
  • Turbines
  • Assortment courses

So let’s dive in!

 

 

Understanding loop constructs is necessary whatever the language you’re programming in. When you’re coming from languages comparable to C++ or JavaScript, it is useful to discover ways to write Pythonic loops.

 

Generate a Sequence of Numbers with vary

 

The vary() operate generates a sequence of numbers, typically used as an iterator in loops.

The vary() operate returns a spread object that begins from 0 by default and goes as much as (however does not embrace) the required quantity.

Right here’s an instance:

for i in vary(5):
    print(i)

 

 

When utilizing the vary() operate, you’ll be able to customise the start line, ending level, and step dimension as wanted.

 

Entry Each Index and Merchandise with enumerate

 

The enumerate() operate is beneficial whenever you need each the index and the worth of every component in an iterable.

On this instance, we use the index to faucet into the fruits listing:

fruits = ["apple", "banana", "cherry"]

for i in vary(len(fruits)):
    print(f"Index {i}: {fruits[i]}")

 

Output >>>

Index 0: apple
Index 1: banana
Index 2: cherry

 

However with the enumerate() operate, you’ll be able to entry each the index and the component like so:

fruits = ["apple", "banana", "cherry"]

for i, fruit in enumerate(fruits):
    print(f"Index {i}: {fruit}")

 

Output >>>

Index 0: apple
Index 1: banana
Index 2: cherry

 

Iterate in Parallel Over A number of Iterables with zip

 

The zip() operate is used to iterate over a number of iterables in parallel. It pairs corresponding parts from completely different iterables collectively.

Contemplate the next instance the place it is advisable loop by way of each names and scores listing:

names = ["Alice", "Bob", "Charlie"]
scores = [95, 89, 78]

for i in vary(len(names)):
    print(f"{names[i]} scored {scores[i]} factors.")

 

This outputs:

Output >>>

Alice scored 95 factors.
Bob scored 89 factors.
Charlie scored 78 factors.

 

Here is a way more readable loop with the zip() operate:

names = ["Alice", "Bob", "Charlie"]
scores = [95, 89, 78]

for identify, rating in zip(names, scores):
    print(f"{identify} scored {rating} factors.")

 

Output >>>

Alice scored 95 factors.
Bob scored 89 factors.
Charlie scored 78 factors.

 

The Pythonic model utilizing zip() is extra elegant and avoids the necessity for handbook indexing—making the code cleaner and extra readable.

 

 

In Python, listing comprehensions and dictionary comprehensions are concise one-liners to create lists and dictionaries, respectively. They’ll additionally embrace conditional statements to filter gadgets based mostly on sure situations.

Let’s begin with the loop model after which transfer on to comprehension expressions for each lists and dictionaries.

 

Checklist Comprehension in Python

 

Say you will have a numbers listing. And also you’d wish to create a squared_numbers listing. You should use a for loop like so:

numbers = [1, 2, 3, 4, 5]
squared_numbers = []

for num in numbers:
    squared_numbers.append(num ** 2)

print(squared_numbers)

 

Output >>> [1, 4, 9, 16, 25]

 

However listing comprehensions present a cleaner and easier syntax to do that. They mean you can create a brand new listing by making use of an expression to every merchandise in an iterable.

 

How To Write Efficient Python Code: A Tutorial for Beginners
Checklist Comprehension Syntax | Picture by Writer

 

Right here’s a concise various utilizing an inventory comprehension expression:

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]

print(squared_numbers)

 

Output >>> [1, 4, 9, 16, 25]

 

Right here, the listing comprehension creates a brand new listing containing the squares of every quantity within the numbers listing.

 

Checklist Comprehension with Conditional Filtering

 

You can even add filtering situations throughout the listing comprehension expression. Contemplate this instance:

numbers = [1, 2, 3, 4, 5]
odd_numbers = [num for num in numbers if num % 2 != 0]

print(odd_numbers)

 

 

On this instance, the listing comprehension creates a brand new listing containing solely the odd numbers from the numbers listing.

 

Dictionary Comprehension in Python

 

With a syntax just like listing comprehension, dictionary comprehension means that you can create dictionaries from current iterables.

 

How To Write Efficient Python Code: A Tutorial for Beginners
Dictionary Comprehension Syntax | Picture by Writer

 

Say you will have a fruits listing. You’d wish to create a dictionary with fruit:len(fruit) key-value pairs.

Right here’s how you are able to do this with a for loop:

fruits = ["apple", "banana", "cherry", "date"]
fruit_lengths = {}

for fruit in fruits:
    fruit_lengths[fruit] = len(fruit)

print(fruit_lengths)

 

Output >>> {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}

 

Let’s now write the dictionary comprehension equal:

fruits = ["apple", "banana", "cherry", "date"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}

print(fruit_lengths)

 

Output >>> {'apple': 5, 'banana': 6, 'cherry': 6, 'date': 4}

 

This dictionary comprehension creates a dictionary the place keys are the fruits and values are the lengths of the fruit names.

 

Dictionary Comprehension with Conditional Filtering

 

Let’s modify our dictionary comprehension expression to incorporate a situation:

fruits = ["apple", "banana", "cherry", "date"]
long_fruit_names = {fruit: len(fruit) for fruit in fruits if len(fruit) > 5}

print(long_fruit_names)

 

Output >>> {'banana': 6, 'cherry': 6}

 

Right here, the dictionary comprehension creates a dictionary with fruit names as keys and their lengths as values, however just for fruits with names longer than 5 characters.

 

 

Context managers in Python assist you handle assets effectively. With context managers, you’ll be able to arrange and tear down (clear up) assets simply. The only and the most typical instance of context managers is in file dealing with.

Take a look at the code snippet under:

filename="somefile.txt"
file = open(filename,'w')
file.write('One thing')

 

It does not shut the file descriptor leading to useful resource leakage.

print(file.closed)
Output >>> False

 

You’ll in all probability give you the next:

filename="somefile.txt"
file = open(filename,'w')
file.write('One thing')
file.shut()

 

Whereas this makes an attempt to shut the descriptor, it doesn’t account for the errors which will come up throughout the write operation.

Nicely, you could now implement exception dealing with to attempt to open a file and write one thing within the absence of any errors:

filename="somefile.txt"
file = open(filename,'w')
strive:
    file.write('One thing')
lastly:
    file.shut()

 

However that is verbose. Now have a look at the next model utilizing the with assertion that helps open() operate which is a context supervisor:

filename="somefile.txt"
with open(filename, 'w') as file:
    file.write('One thing')

print(file.closed)

 

 

We use the with assertion to create a context by which the file is opened. This ensures that the file is correctly closed when the execution exits the with block—even when an exception is raised throughout the operation.

 

 

Turbines present a chic approach to work with giant datasets or infinite sequences—bettering code effectivity and decreasing reminiscence consumption.

 

What Are Turbines?

 

Turbines are features that use the yield key phrase to return values one after the other, preserving their inner state between invocations. In contrast to common features that compute all values without delay and return a whole listing, turbines compute and yield values on-the-fly as they’re requested, making them appropriate for processing giant sequences.

 

How Do Turbines Work?

 

How To Write Efficient Python Code: A Tutorial for Beginners
Picture by Writer

 

Let’s find out how turbines work:

  • A generator operate is outlined like an everyday operate, however as an alternative of utilizing the return key phrase, you’ll use yield to yield a worth.
  • Whenever you name a generator operate, it returns a generator object. Which you’ll iterate over utilizing a loop or by calling subsequent().
  • When the yield assertion is encountered, the operate’s state is saved, and the yielded worth is returned to the caller. The operate’s execution pauses, however its native variables and state are retained.
  • When the generator’s subsequent() technique is named once more, execution resumes from the place it was paused, and the operate continues till the subsequent yield assertion.
  • When the operate exits or raises a StopIterationexception, the generator is taken into account exhausted, and additional calls to subsequent() will elevate StopIteration.

 

Creating Turbines

 

You may create turbines utilizing both generator features or generator expressions.

Right here’s an instance generator operate:

def countdown(n):
    whereas n > 0:
        yield n
        n -= 1

# Utilizing the generator operate
for num in countdown(5):
    print(num)

 

 

Generator expressions are just like listing comprehension however they create turbines as an alternative of lists.

# Generator expression to create a sequence of squares
squares = (x ** 2 for x in vary(1, 6))

# Utilizing the generator expression
for sq. in squares:
    print(sq.)

 

 

 

We’ll wrap up the tutorial by studying about two helpful assortment courses:

 

Extra Readable Tuples with NamedTuple

 

In Python, a namedtuple within the collections module is a subclass of the built-in tuple class. But it surely supplies named fields. Which makes it extra readable and self-documenting than common tuples.

Right here’s an instance of making a easy tuple for a degree in 3D area and accessing the person parts:

# 3D level tuple
coordinate = (1, 2, 3)

# Accessing information utilizing tuple unpacking 
x, y, z = coordinate
print(f"X-coordinate: {x}, Y-coordinate: {y}, Z-coordinate: {z}")

 

Output >>> X-coordinate: 1, Y-coordinate: 2, Z-coordinate: 3

 

And right here’s the namedtuple model:

from collections import namedtuple

# Outline a Coordinate3D namedtuple
Coordinate3D = namedtuple("Coordinate3D", ["x", "y", "z"])

# Making a Coordinate3D object
coordinate = Coordinate3D(1, 2, 3)

print(coordinate)

# Accessing information utilizing named fields
print(f"X-coordinate: {coordinate.x}, Y-coordinate: {coordinate.y}, Z-coordinate: {coordinate.z}")

 

Output >>>

Coordinate3D(x=1, y=2, z=3)
X-coordinate: 1, Y-coordinate: 2, Z-coordinate: 3

 

NamedTuples, due to this fact, allow you to write cleaner and extra maintainable code than common tuples.

 

Use Counter to Simplify Counting

 

Counter is a category within the collections module that’s designed for counting the frequency of parts in an iterable comparable to an inventory or a string). It returns a Counter object with {component:depend} key-value pairs.

Let’s take the instance of counting character frequencies in an extended string.

Right here’s the traditional method to counting character frequencies utilizing loops:

phrase = "incomprehensibilities"

# initialize an empty dictionary to depend characters
char_counts = {}

# Rely character frequencies
for char in phrase:
    if char in char_counts:
        char_counts[char] += 1
    else:
         char_counts[char] = 1

# print out the char_counts dictionary
print(char_counts)

# discover the most typical character
most_common = max(char_counts, key=char_counts.get)

print(f"Most Widespread Character: '{most_common}' (seems {char_counts[most_common]} instances)")

 

We manually iterate by way of the string, replace a dictionary to depend character frequencies, and discover the most typical character.

Output >>>

{'i': 5, 'n': 2, 'c': 1, 'o': 1, 'm': 1, 'p': 1, 'r': 1, 'e': 3, 'h': 1, 's': 2, 'b': 1, 'l': 1, 't': 1}

Most Widespread Character: 'i' (seems 5 instances)

 

Now, let’s obtain the identical job utilizing the Counter  class utilizing the syntax Counter(iterable):

from collections import Counter

phrase = "incomprehensibilities"

# Rely character frequencies utilizing Counter
char_counts = Counter(phrase)

print(char_counts)

# Discover the most typical character
most_common = char_counts.most_common(1)

print(f"Most Widespread Character: '{most_common[0][0]}' (seems {most_common[0][1]} instances)")

 

Output >>>

Counter({'i': 5, 'e': 3, 'n': 2, 's': 2, 'c': 1, 'o': 1, 'm': 1, 'p': 1, 'r': 1, 'h': 1, 'b': 1, 'l': 1, 't': 1})
Most Widespread Character: 'i' (seems 5 instances)

 

So Counter supplies a a lot easier approach to depend character frequencies with out the necessity for handbook iteration and dictionary administration.

 

 

I hope you discovered a couple of helpful ideas so as to add to your Python toolbox. In case you are seeking to be taught Python or are making ready for coding interviews, listed here are a few assets that will help you in your journey:

Glad studying!

 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embrace DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and occasional! At the moment, she’s engaged on studying and sharing her data with the developer group by authoring tutorials, how-to guides, opinion items, and extra.



Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles