Usefulness of one-line statements in Python [closed]

2024/11/21 1:43:04

Is using one line loops, even nested loops always a good practice in Python? I see a lot of people just love "one-liners", but to me they're hard to read sometimes, especially if we're talking about nested loops.

Moreover most of nested loops I've seen so far exceed the recommended 79 characters per line.

So I'd like to know if "one-liners" offer anything extra apart being compact? Do they use less memory maybe?

Answer

Yes, they may be easily faster, since more code may be run in C (in explicit loop all of immediate steps has to be available to interpreter, in one-liner list comprehension it does not have to). There is also overhead of .append method call, method look-up etc. In list comprehension all of that is avoided:

import timeitdef f1():result = []for x in range(100):for y in range(100):result.append(x * y)return resultdef f2():return [x * y for y in range(100) for x in range(100)]print('loop: ', timeit.timeit(f1, number=1000))
print('oneliner:', timeit.timeit(f2, number=1000))

Results (Python 3):

loop:  1.2545137699926272
oneliner: 0.6745600730064325
https://en.xdnf.cn/q/118348.html

Related Q&A

Pack data into binary string in Python [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Parsing Complex Mathematical Functions in Python

Is there a way in Python to parse a mathematical expression in Python that describes a 3D graph? Using other math modules or not. I couldnt seem to find a way for it to handle two inputs.An example of…

How do I check if the user has entered a number? [duplicate]

This question already has answers here:How can I read inputs as numbers?(10 answers)Closed last year.I making a quiz program using Python 3. Im trying to implement checks so that if the user enters a …

high F1 score and low values in confusion matrix

consider I have 2 classes of data and I am using sklearn for classification, def cv_classif_wrapper(classifier, X, y, n_splits=5, random_state=42, verbose=0):cross validation wrappercv = StratifiedKFol…

Replace `\n` in html page with space in python LXML

I have an unclear xml and process it with python lxml module. I want replace all \n in content with space before any processing, how can I do this work for text of all elements.edit my xml example:<…

Basic python. Quick question regarding calling a function [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)Closed 1 year ago.Ive got a basic problem in pyth…

Obtain the duration of a mp4 file [duplicate]

This question already has answers here:How to get the duration of a video in Python?(15 answers)Closed 10 years ago.I need to know the duration of a mp4 file with python 3.3. I search and try to do th…

Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot

%load_ext autoreload %autoreload 2 %matplotlib inlineimport numpy as np import datetime as dt import pickle import pandas as pd import datetime from datetime import timedelta, date from datetime impor…

How to generate the captcha to train with Python

I would like to use deep learning program for recognizing the captcha using keras with python.But the big challenge is to generate massive captcha to train. I want to solve a captcha like thisHow can …

Convert PNG to a binary (base 2) string in Python

I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. Ive tried so many things, but all of them are showing some error