repeat items in a list

Antonio Caminero Garcia tonycamgar at gmail.com
Tue Mar 29 04:43:50 EDT 2016


On Monday, March 28, 2016 at 11:26:08 PM UTC+2, Chris Angelico wrote:
> On Tue, Mar 29, 2016 at 4:30 AM, Rob Gaddi
> <rgaddi at highlandtechnology.invalid> wrote:
> > beliavsky at aol.com wrote:
> >
> >> On Saturday, March 26, 2016 at 7:24:10 PM UTC-4, Erik wrote:
> >>>
> >>> Or, if you want to "import operator" first, you can use 'operator.add'
> >>> instead of the lambda (but you _did_ ask for a one-liner ;)).
> >>>
> >>> Out of interest, why the fascination with one-liners?
> >>
> >> Thanks for your reply. Sometimes when I program in Python I think I am not using the full capabilities of the language, so I want to know if there are
> >> more concise ways of doing things.
> >
> > Concise is only worth so much.  PEP20 tells us "Explicit is better than
> > implicit", "Simple is better than complex" and "If the implementation is
> > hard to explain, it's a bad idea".
> >
> > Python is a beautifully expressive language.  Your goal should not be to
> > write the minimum number of lines of code to accomplish the task.
> > Your goal should be to write the code such that your grandmother can
> > understand it.  That way, when you screw it up, you'll be able to easily
> > figure out where and how you did so.  Or failing that, you can get
> > grangran to show you.
> 
> Just out of interest, did you (generic you) happen to notice Mark's
> suggestion? It's a one-liner that nicely expresses the intention and
> accomplishes the goal:
> 
> yy = [aa for aa in xx for _ in range(nrep)]
> 
> It quietly went through without fanfare, but I would say this is the
> perfect solution to the original problem.
> 
> ChrisA

Of course that's definitely the most pythonic sol to this prob :)! Just wanted to point out the use of the operator "*" in lists.



More information about the Python-list mailing list