multiple ranges to for statement?

Philip Swartzleonard starx at pacbell.net
Tue Apr 9 02:52:28 EDT 2002


Damian Menscher || Mon 08 Apr 2002 11:33:04p:

> I'm hoping to do something along the lines of:
> 
> for i in range(a,b),range(c,d):
>     stuff goes here
> 
> But of course that sets i to the *two* values: range(a,b) and
> range(c,d).  Is there a simple way to get it to take on every value
> from a to b and then every value from c to d?  I would think there
> should be, but I'm a newbie and can't figure it out.
> 
> So far, the best I can think of would be:
> 
> values = range(a,b)
> for i in range(c,d):
>     values.append(i)
> for i in values:
>     stuff goes here
> 
> It just doesn't seem very clean, so I'm wondering if I'm missing
> something obvious.

There may be some gotchas here that i'm not seeing... Anyway, just
remeber that the range command returns a sequence. Sequences can be
concatanated. Here's an exapmle: 

Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> range(1,5)
[1, 2, 3, 4]
>>> range(10,15)
[10, 11, 12, 13, 14]
>>> range(1,5) + range(10,15)
[1, 2, 3, 4, 10, 11, 12, 13, 14]
>>> for x in range(1,5) + range(10,15):
	print x,

1 2 3 4 10 11 12 13 14
>>> 

-- 
Philip Sw "Starweaver" [rasx] :: www.rubydragon.com



More information about the Python-list mailing list