Optimizing Small Python Code

Avi Gross avigross at verizon.net
Tue Jun 22 21:53:03 EDT 2021


I had a similar question, Greg. Optimized for what, indeed.

Some might suggest removing a VISIBLE loop is an optimization and some might
not. 

First you need to look at what your code does. It is fairly primitive. 

Here is a two-line version but is it simpler:

for n in range(1, 7):
   print (n, "\n", ''.join([("\t" + str(x) + "\n") for x in range(0, n)]))

It has the same output:

1 
 	0

2 
 	0
	1
...
6 
 	0
	1
	2
	3
	4
	5

This can be made a one-liner too! LOL!

But there are other optimizations as the calculation sort of keeps
recalculating what is a simple enough pattern.

You can for example in a loop of some kind keep appending to a structure
like a list but perhaps simpler is using indexing into a tuple or list made
in advance and only once. Here is the code that works for any size by
changing the value of "last" without constant recalculation. Is it better?
Who knows?

last = 7; nl = "\n"; tab = "\t"
using = [ tab + str(num) for num in range(0,last)]            
print(''.join([str(n) + nl + nl.join(using[:n]) + nl  for n in range(1,
last)]))

Now why you want this is beyond me!

-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Greg Ewing
Sent: Tuesday, June 22, 2021 7:05 PM
To: python-list at python.org
Subject: Re: Optimizing Small Python Code

On 23/06/21 3:03 am, Kais Ayadi wrote:
> for n in range(1, 7):
>      print (n)
>      for x in range(0, n):
>          print("     ", x)
> 
> can this code be more optimised?

Optimised for what? Readability? Execution speed? Code size?
Memory usage?

-- 
Greg
-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list