[Tutor] Iterate over multiple objects
A.T.Hofkamp
a.t.hofkamp at tue.nl
Wed Oct 29 12:38:31 CET 2008
W W wrote:
> Hi,
> I'm trying to compare two strings because I want to find the difference.
>
> i.e.
> string1 = "foobar"
> string2 = "foobzr"
>
> is there a simple way to do this with a for loop? This is the method I
> tried, but it gives me an error:
>
> In [14]: for x, y in bar[0], bar[1]:
> ....: print x, y
With the zip() function you can merge two sequences into one:
for x, y in zip(string1, string2):
print x, y
will print something like
f f
o o
o o
b b
a z
r r
> for x in xrange(0, len(bar[0])):
> print bar[0][x], bar[1][x] #yes I realize there's no comparison here,
> I know how to do that - this is just a placeholder
Not entirely valid in this case, but the pythonic way to have a value as well
as its index is by using the enumerate() function:
for idx, val in ['A', 'B', 'C']:
print idx, val
will print something like
0 A
1 B
2 C
Good luck,
Albert
More information about the Tutor
mailing list