473,604 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rotating lists?

I need to transform this:

[1,2,3]

into this:

[2,3,1]

(a left-rotation. Actually, any rotation will do).

I tried:

a = a[1:] + a[0]

which doesn't work because there's no __add__ between a list and
integer, and:

a = a[1:].append(a[0])

but it doesn't work, since append returns None :( Right now, I'm doing
it with a temporary variable and it looks ugly - is there an elegant way
of doing it?

Jul 18 '05 #1
9 9185
[Ivan Voras]
I need to transform this:

[1,2,3]

into this:

[2,3,1]

(a left-rotation. Actually, any rotation will do).


For Py2.4, use collections.deq ue.rotate().

For earlier Pythons, concatenate list slices: a[1:] + a[:1]

Raymond Hettinger
Jul 18 '05 #2
Ivan Voras wrote:
I need to transform this:
[1,2,3]
into this:
[2,3,1]

Right now, I'm doing
it with a temporary variable and it looks ugly - is there an elegant way
of doing it?

l = range(1, 4)
l [1, 2, 3] import itertools
list(itertools. islice(itertool s.cycle(l), 1, len(l)+1))

[2, 3, 1]

That is, build an iterator that cycles over l indefinitely,
then take a slice of it starting x items in (where x==1 in
this case) and continuing until you've retrieved a number
of elements equal to the length of the original sequence.

-Peter
Jul 18 '05 #3
Ivan Voras wrote:
I need to transform this:

[1,2,3]

into this:

[2,3,1]

(a left-rotation. Actually, any rotation will do).

I tried:

a = a[1:] + a[0]

which doesn't work because there's no __add__ between a list and
integer, and:

a = a[1:].append(a[0])

but it doesn't work, since append returns None :( Right now, I'm doing
it with a temporary variable and it looks ugly - is there an elegant way
of doing it?


This smells like a use-case for itertools.cycle :
import itertools
c=itertools.cyc le( [1,2,3] )
c.next() 1 c.next() 2 c.next() 3 c.next() 1 c.next()

2

.... or is this not what you need to rotate your lists for?

--Irmen de Jong

Jul 18 '05 #4
Ivan Voras <ivoras@__-geri.cc.fer.hr> writes:
I tried:

a = a[1:] + a[0]

which doesn't work because there's no __add__ between a list and
integer, and:


You meant to say

a = a[1:] + [a[0]]
Jul 18 '05 #5
* Ivan Voras (2004-09-16 00:10 +0200)
I need to transform this:

[1,2,3]

into this:

[2,3,1]

(a left-rotation. Actually, any rotation will do).

I tried:

a = a[1:] + a[0]

which doesn't work because there's no __add__ between a list and
integer, and:

a = a[1:].append(a[0])

but it doesn't work, since append returns None :( Right now, I'm doing
it with a temporary variable and it looks ugly - is there an elegant way
of doing it?


def rotate(seq,
offset):
""" shift seq to the left by offset, with the elements shifted off the
beginning inserted back at the end """
return seq[offset:] + seq[:offset]
Jul 18 '05 #6
Thorsten Kampe wrote:

def rotate(seq,
offset):
""" shift seq to the left by offset, with the elements shifted off the
beginning inserted back at the end """
return seq[offset:] + seq[:offset]

You can also use a generator function:

def rotator(seq, offset=1):
while True:
yield seq
seq = seq[offset:] + seq[:offset]

T = rotator(range(5 ))
T.next()
[0, 1, 2, 3, 4]
T.next()
[1, 2, 3, 4, 0]
T.next()
[2, 3, 4, 0, 1]

You can rotate to the right using a negative offset:
L = rotator( range(5), -1 )
L.next()
[0, 1, 2, 3, 4]
L.next()
[4, 0, 1, 2, 3]
L.next()
[3, 4, 0, 1, 2]
Jul 18 '05 #7
Raymond Hettinger wrote:

For earlier Pythons, concatenate list slices: a[1:] + a[:1]

^^^^^

That's what I missed :) I should've thought of that :)
Thanks!
Jul 18 '05 #8
Irmen de Jong wrote:
This smells like a use-case for itertools.cycle :
>>> import itertools
>>> c=itertools.cyc le( [1,2,3] )
>>> c.next() 1 >>> c.next() 2 >>> c.next() 3 >>> c.next() 1 >>> c.next()

2

... or is this not what you need to rotate your lists for?


No, I don't need an (infinite) cycle, just the rotated list. But thanks,
I didn't notice itertools before :)
Jul 18 '05 #9
[Ivan Voras]> > a = a[1:] + a[0]

which doesn't work because there's no __add__ between a list and
integer, and:
[Paul Rubin]
You meant to say

a = a[1:] + [a[0]]


A better answer is a[1:] + a[:1] which nicely handles lists of length 0 and
length 1 as well as the OP's original example.

The advantage of using slices to extract a single element is that it avoids
IndexErrors for empty lists. This technique comes up often enough that I
thought it worth pointing out here.

Also worth mentioning is that slicing and concatenation are supported by several
sequence types. So, this operation can be abstracted to apply to more than just
lists.

It might also be opportune to point out the virtues of writing a few doctests
that would have surfaced the issues immediately.

Of course, Paul already knows this. This note is for the people who don't.
Raymond Hettinger
def rotate(seq):
""" Rotate the first element to the end of a sequence.

Returns a new sequence of the same type.
The type must support slicing and concatenation.
rotate(range(5) ) [1, 2, 3, 4, 0] rotate(range(1) ) [0] rotate(range(0) ) [] rotate('abc') 'bca' rotate('') '' rotate(tuple('a bc')) ('b', 'c', 'a') rotate(tuple('' ))

()
"""

return seq[1:] + seq[:1]

import doctest
doctest.testmod ()
Jul 18 '05 #10

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

Similar topics

4
2397
by: Ian Hubling | last post by:
I'm trying to complete a rotating banner ad within a page I have. The rotating add has four images that rotate in three-second increments. I've got the images to rotate ok - but now I want to go one step further and can't figure out how to do it... I want to have it so that when the person clicks on the specific ad, they are taken to a URL that is unique to each ad. I presume I would have to surround the img tag with an href tag, but...
1
3209
by: Sandy Bremmer | last post by:
I have seen many Javascripts that rotate images with each load or refresh of the page but so far all I've found require hard coding the image filename into the script. Does anyone know of a script that pulls images randomly from a directory? Thus I would need only add (or delete) images from that directory and they would display on the web page respectively. All the images are the same size (90x90) but there are hundreds so hard coding...
1
2099
by: Grunt | last post by:
Hi, I have been trying to put together a rotating banner. the code works but I am having a problem with the caching of the banner images. no matter what I try the page is constantly reloading the images, even worse they are not loading completely. This version includes a (vain) attempt at forcing the banner images to cache. Apart form the caching problem the scripting seems to work Any help welcomed:
4
5452
by: Roozbeh GHolizadeh | last post by:
Hi there... i think it is a very common problem but i dont know why i didnt find anything good for me on internet... i want to simply rotate an array with 90,180,270 degrees.... here is how i allocated this.... srcimage = (LPBYTE)LocalAlloc(LMEM_FIXED, 320 * 200);
2
6533
by: mistral | last post by:
I want place custom text rotating around analogue clock. Here is javascript that is clise to my task: http://javascript.internet.com/time-date/mousetrailclock.html But it have a few unnecessary features which is difficult to alter. i want: 1. replace week/year/days in external circle with my custom text: 'My custom text'
4
23632
by: Chris Shenton | last post by:
I set this up 3 days ago and have not seen any of the logs I've created this way being rotated. I expected them to rotate every midnight. I'm calling the code that uses this logger many times, each a separate run, if that matters. Am I doing something stupid? I can't find anything on google and don't see anything in the code that would prevent rotating. Thanks.
3
5947
by: avalence | last post by:
Hello, I am trying to create a nice rotating earth globe (on mouse) on my web site, in order to display my professional relationships all over the world. The best way seems to be a javascript. In fact I still hesitate between java and javascript. My question is how can I create a interacting globe using a satellite photo. This is a very usefull applet for everybody. All suggestion welcome! Thanks Arnaud
1
2560
by: AR123 | last post by:
Hi I want to set up a rotating banner. Not sure how to incorporate my rotating banner code into the code below. I want the rotating banner to be the main feature image? This is set up in mediasurface My code is: <!-- start page container --> <div id="pageContainer"> <!-- start middle content area --> <div id="genericMiddle">
0
4043
by: empiresolutions | last post by:
I need to set up a rotating proxy for an application i am building. I have a cURL script that reads a page, but i need to seem like its not being called from the same IP address each time. I would like to have a list of proxies that i can rotate between each call i make. I have looked at Glype and PHPproxy but both i cannot get to work correctly. Does anybody have any suggestions, script examples or good info web pages they can provide. I...
0
7997
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7929
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
8406
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
8065
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
8274
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6737
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...
1
5882
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2433
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
0
1262
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.