* Paul Rudin:
Sebastian <sebastian.lan...@gmx.de> writes:

I have an array  x=[1,2,3]

In python such an object is called a "list".

(In cpython it's implemented as an automatically resizable array.)

I don't think the OP's terminology needs correction.

A Python "list" is an array functionality-wise.

If one isn't observant of that fact then one ends up with O(n^2) time for the simplest things.

Using the term "array" accentuates and clarifies this most important aspect.

Using the misleading term "list", even if that's the type's name in Python, hides this most important aspect, and so is not, IMHO, a Good Idea except where it really matters that it's a 'list' array as opposed to, say, a 'tuple' array.


Is there an operator which I can use to get the result
[1,1,1,2,2,2,3,3,3] ?

There's no operator that will give you that directly - but there are
plenty of one-liners that will yield that list.
e.g:

list(itertools.chain(*([x]*3 for x in [1,2,3])))
[1, 1, 1, 2, 2, 2, 3, 3, 3]

And I think it's worth noting that, for the general case, this notation is also hiding a gross inefficiency, first constructing sub-arrays and then copying them and joining them.

It doesn't even buy clarity.

So, just

>>> def repeat_items_in( s, n ):
...   a = []
...   for item in s:
...     for i in range( n ):
...       a.append( item )
...   return a
...
>>> repeat_items_in( [1, 2, 3], 3 )
[1, 1, 1, 2, 2, 2, 3, 3, 3]
>>> _

And if one absolutely feels like trading some efficiency and clarity for some more functional-programming expression like thing (I don't understand why people desire that!), just replace the 'append' line with a 'yield' and then write

  list( repeat_items_in( [1, 2, 3], 3 ) )

Re the thing I don't understand: it's the same in C++, people using hours on figuring out how to do something very simple in an ungrokkable indirect and "compiled" way using template metaprogramming stuff, when they could just write a simple 'for' loop and be done with in, say, 3 seconds, and much clearer too!


Cheers,

- Alf
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to