473,385 Members | 2,028 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,385 software developers and data experts.

Iterating Through List or Tuple

Is there a way to loop or iterate through a list/tuple in such a way
that when you reach the end, you start over at the beginning? For
example, suppose I define a list "daysOfWeek" such that:
>>daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
If today is Sunday, I can set the variable "day" to today by:
>>i = iter(daysOfWeek)
day = i.next()
print day
sunday

If I want to find out the day of the week 2 days from now, then this
code works ok:
>>for x in xrange(2): day = i.next()
>>print day
tuesday

However, when extending my range beyond the number of items in the
list, I receive an error. For example, if I want to find out the day
of the week 11 days from today, I get this:
>>for x in xrange(11): day = i.next()

Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
for x in xrange(11): day = i.next()
StopIteration

Is there a way to easily loop through a list or tuple (and starting
over at the beginning when reaching the end) without having to resort
to an "if" or "while" statement?

(My question concerns the more general use of lists and tuples, not
necessarily determining days of the week. I know about using "import
datetime" and "from calendar import weekday" but thought that using
the days of the week would best illustrate my problem.)

As always, thanks in advance.

Samir
Jul 22 '08 #1
4 5033
Samir wrote:
Is there a way to loop or iterate through a list/tuple in such a way
that when you reach the end, you start over at the beginning? For
example, suppose I define a list "daysOfWeek" such that:
>>>daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
>>import itertools
help(itertools.cycle)
Help on class cycle in module itertools:

class cycle(__builtin__.object)
| cycle(iterable) --cycle object
|
| Return elements from the iterable until it is exhausted.
| Then repeat the sequence indefinitely.

....
>>L = [1, 2, 3]
for i, x in enumerate(itertools.cycle(L)):
.... print i, x
.... if i >= 10:
.... break
....
0 1
1 2
2 3
3 1
4 2
5 3
6 1
7 2
8 3
9 1
10 2
>>>
</F>

Jul 22 '08 #2
On Tue, 22 Jul 2008 14:43:10 -0700, Samir wrote:
Is there a way to loop or iterate through a list/tuple in such a way
that when you reach the end, you start over at the beginning? For
example, suppose I define a list "daysOfWeek" such that:
>>>daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']

If today is Sunday, I can set the variable "day" to today by:
>>>i = iter(daysOfWeek)
day = i.next()
print day
sunday

If I want to find out the day of the week 2 days from now, then this
code works ok:
>>>for x in xrange(2): day = i.next()
>>>print day
tuesday

However, when extending my range beyond the number of items in the
list, I receive an error. For example, if I want to find out the day
of the week 11 days from today, I get this:
>>>for x in xrange(11): day = i.next()


Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
for x in xrange(11): day = i.next()
StopIteration

Is there a way to easily loop through a list or tuple (and starting
over at the beginning when reaching the end) without having to resort
to an "if" or "while" statement?
For sequences: days_of_week[(today + offset) % len(days_of_week)]

For iterables in general: `itertools.cycle()`

Ciao,
Marc 'BlackJack' Rintsch
Jul 22 '08 #3
Samir wrote:
Is there a way to loop or iterate through a list/tuple in such a way
that when you reach the end, you start over at the beginning? For
example, suppose I define a list "daysOfWeek" such that:
>>>daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']

If today is Sunday, I can set the variable "day" to today by:
>>>i = iter(daysOfWeek)
day = i.next()
print day
sunday

If I want to find out the day of the week 2 days from now, then this
code works ok:
>>>for x in xrange(2): day = i.next()
>>>print day
tuesday

However, when extending my range beyond the number of items in the
list, I receive an error. For example, if I want to find out the day
of the week 11 days from today, I get this:
>>>for x in xrange(11): day = i.next()


Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
for x in xrange(11): day = i.next()
StopIteration

Is there a way to easily loop through a list or tuple (and starting
over at the beginning when reaching the end) without having to resort
to an "if" or "while" statement?

(My question concerns the more general use of lists and tuples, not
necessarily determining days of the week. I know about using "import
datetime" and "from calendar import weekday" but thought that using
the days of the week would best illustrate my problem.)

As always, thanks in advance.

Samir
>>import itertools
i = itertools.cycle(daysOfWeek)
i.next()
'sunday'
>>i.next()
'monday'
..
..
..
>>i.next()
'saturday'
>>i.next()
'sunday'

-Larry
Jul 22 '08 #4
Fredrik, Marc, Larry -- Thank you all for your very fast and
informative replies. I had not come across "itertools" in my search.
This group is a great resource.

Samir

Jul 22 '08 #5

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

Similar topics

9
by: Yomanium Yoth Taripoät II | last post by:
HI, 1) what are the differences between list and tuple? 2) how to concatenate tuple and list? no method, no opérator? 3) im looking the fucking manual, and cant add value in my tuple, when it...
2
by: Dirk Zimmermann | last post by:
Hi, I have the following problem: I have a list with tuples in it, looking like this: myList = (I want to store a number calculated from a file together with the file.) Than I want to...
4
by: GrelEns | last post by:
hello, i wonder if this possible to subclass a list or a tuple and add more attributes ? also does someone have a link to how well define is own iterable object ? what i was expecting was...
4
by: Fernando Rodríguez | last post by:
Hi, While iterating through a list I'd like to know not just the current element, but also its index. Is there a better way than this: i = 0 newList = for element in aList:...
2
by: Ishwar Rattan | last post by:
I am a little confused about a list and a tuple. Both can have dissimilar data-type elements, can be returned by functions. The only difference that I see is that list is mutable and tuple is...
17
by: Gal Diskin | last post by:
Hi, I am writing a code that needs to iterate over 3 lists at the same time, i.e something like this: for x1 in l1: for x2 in l2: for x3 in l3: print "do something with", x1, x2, x3 What I...
6
by: fdu.xiaojf | last post by:
Hi all, I can use list comprehension to create list quickly. So I expected that I can created tuple quickly with the same syntax. But I found that the same syntax will get a generator, not a...
13
by: kj | last post by:
Is there a special pythonic idiom for iterating over a list (or tuple) two elements at a time? I mean, other than for i in range(0, len(a), 2): frobnicate(a, a) ?
0
by: Hatem Nassrat | last post by:
on Wed Jun 13 10:17:24 CEST 2007, Diez B. Roggisch deets at nospam.web.de wrote: Well I have looked into this and it seems that using the list comprehension is faster, which is...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.