473,405 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Idiomatic way of repeating items in a sequence.

alr
I need to repeat each item in a list n times, like this function does:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist

Output:
repeatitems(['a', 'b', 'c'], 3)

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

Clear and simple. But i wonder if there is a more idiomatic way. Surely not this:

def repeatitems(sequence, repetitions):
return reduce(lambda l, i: l + i, [[item] * repetitions for item in sequence])

?
Jul 18 '05 #1
12 8090
alr wrote:
I need to repeat each item in a list n times, like this function does:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist

I would make just a minor change:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist += repetitions*[item]
return newlist
regards Max M

Jul 18 '05 #2
an***@wmdata.com (alr) wrote in
news:f5*************************@posting.google.co m:
I need to repeat each item in a list n times, like this function does:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist

Output:
>>> repeatitems(['a', 'b', 'c'], 3)

['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c']

Clear and simple. But i wonder if there is a more idiomatic way.


The most obvious one that springs to mind is just a slight simplification
of your version:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #3
alr wrote:
I need to repeat each item in a list n times, like this function does:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitions):
newlist.append(item)
return newlist
.... But i wonder if there is a more idiomatic way.


How about this?

def repeatItems(sequence, repetitions):
return [[item]*repetitions for item in sequence]
Jul 18 '05 #4

"Peter Otten" <__*******@web.de> wrote in message news:bd*************@news.t-online.com...
How about this?

def repeatItems(sequence, repetitions):
return [[item]*repetitions for item in sequence]


Unfortunately that is equivalent to:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.append([item] * repetitions)
return newlist

and not:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
Jul 18 '05 #5
Duncan Booth <du****@NOSPAMrcp.co.uk> wrote in
news:Xn***************************@127.0.0.1:
The most obvious one that springs to mind is just a slight
simplification of your version:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist


Or, if you are in a "I've got a new toy to play with" mood you could use
itertools from Python 2.3 to obfuscate it somewhat:

from itertools import chain, izip, repeat
def repeatiterate(sequence, repetitions):
return chain(*izip(*repeat(sequence, repetitions)))

This version returns an iterator, so you might want to throw in a call to
'list' if you want to do anything other than iterating over the result.

--
Duncan Booth du****@rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #6
Richard Brodie wrote:
Unfortunately that is equivalent to:

def repeatitems(sequence, repetitions):
newlist = []
for item in sequence:
newlist.append([item] * repetitions)
return newlist


.... but it looked so good. I should have tested it, though.
Je suis desole :-(
Jul 18 '05 #7

"alr" <an***@wmdata.com> wrote in message
news:f5*************************@posting.google.co m...
I need to repeat each item in a list n times, like this function

does:

Is this really the right question? Any code that requires such an
n-repeat list *could* be rewritten (if you own it) to use the replist
in condensed form: (items, n). If this is not possible, one could
also define a replist class with a __getitem__(self, index) that
divides index by self.n and an __iter__() that returns an appropriate
generator.

Terry J. Reedy


Jul 18 '05 #8
>>>>> "alr" == alr <an***@wmdata.com> writes:

alr> reduce(lambda l, i: l + i, [[item] * repetitions for item in

This doesn't look too bad to me, but perhaps list comprehensions are
clearer?

seq = ['a', 'b', 'c']
print [x for x in seq for x in seq]

Jul 18 '05 #9
>>>>> "alr" == alr <an***@wmdata.com> writes:

alr> reduce(lambda l, i: l + i, [[item] * repetitions for item in
alr> sequence])
Oops, premature hit of send key. What I meant to say was

seq = ['a', 'b', 'c']
print [x for x in seq for i in range(len(seq))]

JDH
Jul 18 '05 #10
John Hunter wrote:
This doesn't look too bad to me, but perhaps list comprehensions are
clearer?

seq = ['a', 'b', 'c']
print [x for x in seq for x in seq]
def repeat3( sequence, count=1 ): .... return [x for x in sequence for i in range(count) ]
.... repeat3( [2,3,4], 3 ) [2, 2, 2, 3, 3, 3, 4, 4, 4]

I *think* is what you were suggesting, and is indeed very clear. For
those into generators, this is fun (but has no huge advantage if you
wind up using repeat instead of irepeat, or if you're using small
sequences):
from __future__ import generators
def irepeat( sequence, count=1 ): .... countSet = range(count)
.... for item in sequence:
.... for i in countSet:
.... yield item
.... def repeat( sequence, count = 1 ): .... return list(irepeat(sequence, count))
.... repeat( [2,3,4], 3 )

[2, 2, 2, 3, 3, 3, 4, 4, 4]

Enjoy,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/


Jul 18 '05 #11
Here's one:

def repeatitems(sequence, repetitions):
r = [None] * repetitions
return [i for i in sequence for j in r]

Here's another, using generator functions (so the return is an iterator,
not a list):

def repeatitems(sequence, repetitions):
r = [None] * repetitions
for item in sequence:
for i in r:
yield item

In both cases I've performed an "optimization" by precomputing a list
with len(repetitions) instead of computing it once for each item in
sequence. Whether this makes a difference, I don't know.

Jeff

Jul 18 '05 #12
alr
Wow, tanks for alle the replies. My favourite is John Hunters/Bob
Gailers solution ([x for x in seq for i in range(repetitions)]). I had
forgotten that you could have nested for statements in list
literals... Aahz's point is taken. I happen to need to repeat lists of
strings (which are immutable), but that's not what i asked about now
is it. :-)

--
Regards
André Risnes
Jul 18 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Charlotte Henkle | last post by:
Hello; I'm pondering how to count the number of times an item appears in total in a nested list. For example: myList=,,] I'd like to know that a appeared three times, and b appeared twice,...
6
by: M. Clift | last post by:
Hi All, I have tried to come up with a way to do this myself and all I end up with is very long code. What I have is a say item1, item4, item2, item1 etc... What I want to do is append to...
0
by: Neil Waldie | last post by:
I am trying to code a class for use with the XMLSerializer that can produce XML valid for the following schema (fragment): <xs:element name="Group"> <xs:complexType> <xs:sequence minOccurs="1"...
2
by: nickheppleston | last post by:
I'm trying to iterate through repeating elements to extract data using libxml2 but I'm having zero luck - any help would be appreciated. My XML source is similar to the following - I'm trying to...
2
by: MCM | last post by:
I'm working on a plotting control. The plotting control will have a context menu with basic commands for "scaling", "zooming", etc. Is there a way that, from the parent form, I can add more...
10
by: lifity | last post by:
hi, i am stuck on part of my project and very new to VB. i had cut my picture into 6 equals part but need to display them randomly, without repeating the same part of the pic again, in random...
0
by: Gammazoni | last post by:
Hello, I have a code like that, which has been using by me, but now I need another one, which won't differ a lot, I hope. Please, analize it, I believe that here I'll find somebody with large luggage...
4
by: zr | last post by:
Hi, i need to read a text file which contains a list of items, all of type ItemType, separated by whitespace and newlines. For each line, there will be a vector<ItemTypeobject that will store...
1
by: nirmala26 | last post by:
Hi All, Language Used - C#.net I have a web application containing 6 aspx pages and their code files. Now I want to design a automatic display of these webpages in sequence. In detail, once i...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.