1

I am learning python and have a very simple query

Basically what exactly does this code below mean in english

for i in values : 
   for x in othervalues :

does it mean compare all values in values to all values in othervalues ?

johndoe12345
  • 291
  • 2
  • 4
  • 13
  • 1
    Go through `values` using `i` to represent each value. Each time, go through `othervalues` using `x` to represent each othervalue. It doesn't say anything about comparing things. – khelwood Nov 15 '15 at 11:56
  • Are you hiding a third line under the second `for` from us? – Dimitris Fasarakis Hilliard Nov 15 '15 at 11:57
  • yeah there would be an if as third line but i just wanted to know was there actual any comarison done in the above lines. – johndoe12345 Nov 15 '15 at 12:04
  • no, no comparison involved. Those two `for` loops iterate on the given sequences. The `StopIteration` exception is raised when the end of a sequence is reached. – Pynchia Nov 15 '15 at 12:17

1 Answers1

1

As @khelwood said, it simply iterates on two loops.

It iterates through the values in values, assigning each value to the variable i

Inside such loop it does the same thing, iterating on the values of othervalues and assigning each value to the variable x

You can verify it simply adding a print statement inside the loop, that shows the values of i and x

for i in values : 
    for x in othervalues :
        print('i={}, x={}'.format(i,x))

e.g. with an input of

values = 'abc'
othervalues = [1, 2, 3, 4, 5]

it produces

i=a, x=1
i=a, x=2
i=a, x=3
i=a, x=4
i=a, x=5
i=b, x=1
i=b, x=2
i=b, x=3
i=b, x=4
i=b, x=5
i=c, x=1
i=c, x=2
i=c, x=3
i=c, x=4
i=c, x=5

Please make sure you understand how iteration works in python, reading the official docs and this SO Q&A and more tutorials you can find on the internet.

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43