Reputation: 549
I have a list test_cases
with class objects. Every object has an attribute called ident
.
I want to iterate over all objects from list and do something with value under ident
This is my code:
class TestCase:
def __init__(self, title, ident, description):
self.title = title
self.ident = ident
self.description = description
test_cases = []
test_cases.append(TestCase(**tc_dict))
i = 0
while i != len(test_cases):
print(test_cases[i].ident)
i += 1
It works fine, but what I want to ask, if there is a more 'pythonic' way to do that.
Upvotes: 12
Views: 54737
Reputation: 21941
Use a for
loop to iterate over the objects directly (as opposed to iterating over their indexes):
for test_case in test_cases:
print test_case.ident
This is the generic way, and should be used 99% of the time when you want to loop over objects. It works perfectly here and is probably the ideal solution.
If you ever do need the indexes, you should use enumerate()
:
for index, test_case in enumerate(test_cases):
print index, test_case.ident
It's still looping over the objects, but it's simultaneously receiving their indexes from enumerate
.
In your particular use case, there is another option though. If you have a lot of objects, it might be slow to print them out one by one (calling print
is rather expensive). If performance turns out to be an issue, you can use str.join
to join the values beforehand, and then print it all out once:
print '\n'.join(tc.ident for tc in test_cases)
I personally recommend the first method, and would only refer to the latter when you need to print out a lot of stuff and actually can see the performance issue with your naked eye.
Upvotes: 21
Reputation: 1141
First, you can replace your while loop by a for loop
for i in range(len(test_cases)):
print test_cases[i].indent
However, looping over an index and accessing an element by using that index is often a code smell in python. Better would simply be to loop over the elements
for test_case in test_cases:
print test_case.indent
Upvotes: 3