Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (45.3k points)

I have these two statements

return self.getData() if self.getData() else ''

and

return self.getData() or ''

I want to know if they are same or there is any difference

1 Answer

0 votes
by (16.8k points)

They will have the same result, since both treat self.getData()'s result in a boolean context, but beware:

1) return self.getData() if self.getData() else ''

will run the function getData twice, while

2) return self.getData() or ''

will only run it once. This can be important if getData() takes a while to execute, and it means that 1) is not the same as 2) if the function getData() has any side effects.

Stick with 2)

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...