Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm still learning python/jython, so sorry if I ask silly questions.

I have this for loop in java, but I have no idea how to code it in Python/Jython, since it insists using "in"...

for(String effectString : config.getStringList("string.list") {
// Do something

I tried:

for effectString = config.getStringList("string.list"):

and

for effectString in config.getStringList("string.list"):

but then I realised that I didn't defined effectString and, actually, effectString is config.getStringList("string.list")...

Thanks for explanation in advance, Amar!

share|improve this question
2  
Your last example is syntactically correct. –  Hyperboreus Nov 29 '13 at 19:02
    
In Python you don't need to define a variable before you use it in a for statement, so assuming config.getStringList("stringlist") is a generator of some sort, then you're all set –  MattDMo Nov 29 '13 at 19:03

3 Answers 3

up vote 0 down vote accepted

Your following syntax is correct if config.getStringList("string.list") returns a collection.

for effectString in config.getStringList("string.list"):

Syntax For loops

share|improve this answer
    
It looks like it was my mistake, probably I missed something while testing that, anyway, thanks for explanation! –  user2971511 Nov 29 '13 at 19:29

You can use a for loop in python to iterate over iterables.

Iterables can be a list, dict, generator objects, etc.

For example

>>> for num in [1, 2, 3, 4]:
...     print num    
1
2
3
4
>>> my_nums = ("0", "1", "2")
>>> for num in my_nums:
...     print num
0
1
2
>>> my_classes = [int, float, abs, str]
>>> for cls in my_classes:
...     print cls
<type 'int'>
<type 'float'>
<built-in function abs>
<type 'str'>

For more details, have a look at the Python Docs.

share|improve this answer

This syntax:

for effectString in config.getStringList("string.list"):

is correct. When using for loops in Python you implicitly create a local variable.

In some languages, for (i=0; i<10; i++) might be how a for loop would look. There, you explicitly initialize the variable i, to be used in the body of the loop. In Python, for something in iterable creates the local variable something.

It is also worth noting that the variable persists after the loop is finished:

>>> for i in range(10):
        pass
>>> print(i)
9
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.