473,729 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(seq uence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitio ns):
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(seq uence, repetitions):
return reduce(lambda l, i: l + i, [[item] * repetitions for item in sequence])

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

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

I would make just a minor change:

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

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

def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitio ns):
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(seq uence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\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(seq uence, repetitions):
newlist = []
for item in sequence:
for i in range(repetitio ns):
newlist.append( item)
return newlist
.... But i wonder if there is a more idiomatic way.


How about this?

def repeatItems(seq uence, 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(seq uence, repetitions):
return [[item]*repetitions for item in sequence]


Unfortunately that is equivalent to:

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

and not:

def repeatitems(seq uence, repetitions):
newlist = []
for item in sequence:
newlist.extend([item] * repetitions)
return newlist
Jul 18 '05 #5
Duncan Booth <du****@NOSPAMr cp.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(seq uence, 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(s equence, repetitions):
return chain(*izip(*re peat(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.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #6
Richard Brodie wrote:
Unfortunately that is equivalent to:

def repeatitems(seq uence, 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.c om> wrote in message
news:f5******** *************** **@posting.goog le.com...
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__(sel f, 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.c om> 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.c om> 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

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

Similar topics

8
13082
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, and the rest appeard only once.
6
1522
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 each item an extra value depending on the previous item.
0
1187
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" maxOccurs="unbounded"> <xs:element name="SubElement1" /> <xs:element minOccurs="0" maxOccurs="1" name="SubElement2" /> <xs:element minOccurs="0" maxOccurs="1" name="SubElement3" /> </xs:sequence>
2
6630
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 extract the line number and product code from the repeating line elements: <order xmlns="some-ns"> <header> <orderno>123456</orderno> </header>
2
5907
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 commands to the control's context menu? I'm envisioning a case where the control has a set of context menu items, and the parent form also has a set of context menu items. Thanks.
10
3401
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 sequence. eg, pic1,pic2,pic3,pic4,pic5,pic6 to ==> pic3,pic2,pic6,pic1,pic5,pic4 below are part of my code Dim theImage(0 To 7) As Object Dim myArray(0 To 7) As Object
0
1386
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 of experience. Please, write any suggestions you have. Sub test() Dim ws As Worksheet, a, i As Long, ii As Long, b(), n As Long, w(), e With CreateObject("Scripting.Dictionary") For Each ws In Worksheets With...
4
2282
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 the integers read in that line. There will be a single vector<vector<ItemType>object that will stores all of the vector<ItemTypeobjects mentioned in the previous sentence. I wrote a quick implementation and it seems to be working, but i would like...
1
1625
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 open the weblink - it should show the Main webpage (Main.aspx) for 2 mins, then automatically redirect to the second webpage (Second.aspx), display this for 2 mins and then redirect to the third and so on... Once the 6th webpage (Six.aspx) is displayed...
0
8761
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9281
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8148
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.