Most elegant way to do something N times

Avi Gross avigross at verizon.net
Mon Dec 23 20:51:24 EST 2019


I would like some examples of how one does what is requested in some other
programming languages. I doubt there is much need of a shorter way to do
anything N times and throw away any return values.

Python has many ways to do just about anything. It has some features which
suggest a particular way that many accept as pythonic. If there was a need
to do something like:

	repeat_n( times=6, funct=fun, moreargs=whatever)

then someone probably would have included it.

So, yes, a fairly short and often clear method is:

	for _ in range(6): ...

And others have shown multiple ways to get something similar to what you
want. Want real clarity for exactly six times?

# Do this six times:
whatever()
whatever()
whatever()
whatever()
whatever()
whatever()

Heck, the above may even run faster without loop overhead.

Like Marco, it would be interesting to hear actual examples where it makes
sense to repeat something the same way N times. Many such examples do have
ways to do it trivially. I mean if you want to line up text and need N
copies of say an asterisk or space, you can often use something like 

"*" * 5

And the techniques to repeat some function call N times with the arguments
varying each time, can be handled many other ways too including map
functions and comprehensions.

I am left wondering if this is not about the real world but simply an
academic exercise.
-----Original Message-----
From: Python-list <python-list-bounces+avigross=verizon.net at python.org> On
Behalf Of Marco Sulla
Sent: Monday, December 23, 2019 6:12 PM
To: Batuhan Taskaya
<isidentical.gmail.com-mail.python.org.marco.sulla.e4ward.com at jq2z635tc37.re
ply.e4ward.com>
Cc: Ian Kelly ian.g.kelly-at-gmail.com |python-list at python.org|
<python-list at python.org>
Subject: Re: Most elegant way to do something N times

>
> I encounter with cases like doing a function 6 time with no argument, 
> or same arguments over and over or doing some structral thing N times 
> and I dont know how elegant I can express that to the code.
>

??? Excuse me, but why you needed to call the same function SIX times? This
seems to me not elegant in primis.

Can you give us a practical example?


On Sun, 22 Dec 2019 at 21:38, Batuhan Taskaya <isidentical at gmail.com> wrote:

> I encounter with cases like doing a function 6 time with no argument, 
> or same arguments over and over or doing some structral thing N times 
> and I dont know how elegant I can express that to the code. I dont 
> know why but I dont like this for _ in range(n): do() thing. Any
suggestions?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list