• Latest
  • Trending
11 Bite-Sized Python Recipes You Must Know

11 Bite-Sized Python Recipes You Must Know

March 24, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Friday, 17 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

11 Bite-Sized Python Recipes You Must Know

by ITECHNEWS
March 24, 2022
in Data Science, Leading Stories
0 0
0
11 Bite-Sized Python Recipes You Must Know

Many programmers like Python for its simple and concise syntax. These Python recipes are small sample programs that you can use to solve common daily problems.

Use these easy-to-digest Python recipes and take your coding efficiency to the next level.

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program

1. Extract a Subset of a Dictionary

You can extract a subset of a dictionary using the dictionary comprehension method.

test_marks = {
 'Alex' : 50,
 'Adam' : 43,
 'Eva' : 96,
 'Smith' : 66,
 'Andrew' : 74
}
 
greater_than_60 = { key:value for key, value in test_marks.items() if value > 60 }
print(greater_than_60)
 
students = { 'Alex', 'Adam', 'Andrew'}
a_students_dict = { key:value for key,value in test_marks.items() if key in students }
print(a_students_dict)

Output:

{'Eva': 96, 'Smith': 66, 'Andrew': 74}
{'Alex': 50, 'Adam': 43, 'Andrew': 74}

2. Search and Replace Text

You can search and replace a simple text pattern in a string using the str.replace() method.

str = "Peter Piper picked a peck of pickled peppers"
str = str.replace("Piper", "Parker")
print(str)

Output:

Peter Parker picked a peck of pickled peppers

For more complicated patterns, you can use the sub() method from the re library. Regular Expressions in Python make the task a lot easier for complicated patterns.

import re
str = "this is a variable name"
result = re.sub('\⁠s', '_', str)
print(result)

Output:

this_is_a_variable_name

The above code replaces the white-space character with an underscore character.

3. Filter Sequence Elements

You can filter elements from a sequence according to certain conditions using list comprehension.

list = [32, 45, 23, 78, 56, 87, 25, 89, 66]
 
# Filtering list where elements are greater than 50
filtered_list = [ele for ele in list if ele>50]
print(filtered_list)

Output:

[78, 56, 87, 89, 66]

4. Align Text Strings

You can align text strings using the ljust(), rjust(), and center() methods. These methods left-justify, right-justify, and center a string in a field of a given width.

str = "Python is best"
print(str.ljust(20))
print(str.center(20))
print(str.rjust(20))

Output:

Python is best 
 Python is best 
 Python is best

These methods also accept an optional fill character.

str = "Python is best"
print(str.ljust(20, '#'))
print(str.center(20, '#'))
print(str.rjust(20, '#'))

Output:

Python is best######
###Python is best###
######Python is best

Note: You can also use the format() function to align strings.

5. Convert Strings Into Datetimes

You can use the strptime() method from the datetime class to convert a string representation of the​ date/time into a date object.

from datetime import datetime
str = '2022-01-03'
print(str)
print(type(str))
datetime_object = datetime.strptime(str, '%Y-%m-%d')
print(datetime_object)
print(type(datetime_object))

Output:

2022-01-03
<class 'str'>
2022-01-03 00:00:00
<class 'datetime.datetime'>

Note: If the string argument is not consistent with the format parameter, the strptime()method will not work.

6. Unpack a Sequence Into Separate Variables

You can unpack any sequence into variables using the assignment operation. This method works as long as the number of variables and the structure of the sequence match with each other.

Unpacking Tuples

tup = (12, 23, 34, 45, 56)
a, b, c, d, e = tup
print(a)
print(d)

Output:

12
45

Unpacking Lists

list = ["Hey", 23, 0.34, (55, 76)]
a, b, c, d = list
print(a)
print(d)

Output:

Hey
(55, 76)

Unpacking Strings

str = "Hello"
ch1, ch2, ch3, ch4, ch5 = str
print(ch1)

Output:

H

If the number of variables and the structure of the sequence mismatch, you’ll get an error:

list = ["Hey", 23, 0.34, (55, 76)]
a, b, c = list

Output:

Traceback (most recent call last):
File "unpack-list-error.py", line 2, in <module>
a, b, c = list
ValueError: too many values to unpack (expected 3)

7. Writing Functions That Accept Any Number of Positional Arguments

You need to use a * argument to accept any number of positional arguments.

def sumOfElements(firstTerm, *otherTerms):
 s = firstTerm + sum(otherTerms)
 print(s)
sumOfElements(10, 10, 10, 10, 10)
sumOfElements(10)
sumOfElements(10, 10, 10)

Output:

50
10
30

8. Return Multiple Values from a Function

You can return multiple values from a function using a tuple, list, or dictionary.

def returnMultipleSports():
 sport1 = "football"
 sport2 = "cricket"
 sport3 = "basketball"
 return sport1, sport2, sport3
sports = returnMultipleSports()
print(sports)

Output:

('football', 'cricket', 'basketball')

In the above example, the function returns a tuple. You can unpack the tuple and use the returned values.

def returnMultipleLanguages():
 language1 = "English"
 language2 = "Hindi"
 language3 = "French"
 return [language1, language2, language3]
languages = returnMultipleLanguages()
print(languages)

Output:

['English', 'Hindi', 'French']

In this example, the function returns a list.

9. Iterate in Reverse

You can iterate over a sequence in reverse order using the reversed() function, range()function, or using the slicing technique.

Iterating in Reverse Using the reversed() Function

list1 = [1, 2, 3, 4, 5, 6, 7]
for elem in reversed(list1):
 print(elem)

Output:

7
6
5
4
3
2
1

Iterating in Reverse Using the range() Function

list1 = [1, 2, 3, 4, 5, 6, 7]
for i in range(len(list1) - 1, -1, -1):
 print(list1[i])

Output:

7
6
5
4
3
2
1

Iterating in Reverse Using the Slicing Technique

list1 = [1, 2, 3, 4, 5, 6, 7]
for elem in list1[::-1]:
 print(elem)

Output:

7
6
5
4
3
2
1

10. Reading and Writing JSON to a File

You can work with JSON data using the built-in json package in Python.

Writing JSON to a File

You can write JSON to a file using the json.dump() method.

import json
languages = {
 "Python" : "Guido van Rossum",
 "C++" : "Bjarne Stroustrup",
 "Java" : "James Gosling"
}
with open("lang.json", "w") as output:
 json.dump(languages, output)

This will create a new file named lang.json.

Reading JSON From a File

You can read JSON from a file using the json.load() function. This function loads the JSON data from a JSON file into a dictionary.

import json
with open('lang.json', 'r') as o:
 jsonData = json.load(o)
print(jsonData)

Output:

{'Python': 'Guido van Rossum', 'C++': 'Bjarne Stroustrup', 'Java': 'James Gosling'}

11. Writing to a File That Doesn’t Already Exist

If you want to write to a file only if it doesn’t already exist, you need to open the file in x mode (exclusive creation mode).

with open('lorem.txt', 'x') as f:
 f.write('lorem ipsum')

If the file lorem.txt already exists, this code will cause Python to throw a FileExistsError.

If you want to have a look at the complete source code used in this article, here’s the GitHub repository.

Make Your Code Robust With Built-In Python Functions

Use functions to break a program into modular chunks and perform specific tasks. Python provides many built-in functions like range(), slice(), sorted(), abs(), and so on that can make your tasks a lot easier. Make use of these built-in functions to write a more readable and functional code.

Source: YUVRAJ CHANDRA
Via: makeuseof
Tags: Python programmers
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version