I have an example array like:

array = [1, 2, 3, 4, 5, 6]

Every of this numbers refers to an object that has text property. I want to make sure that every of these object has the same text value. Currently I do it like this:

correct = []
for number in array:
  if(object[number].text == "Sample"):
if correct.length == array.length:
  return True

Is there a more efficient way to do this, like with lambda function or?

  • \$\begingroup\$ I can't help but feel that there's some context here that you are not showing us. What is the problem that you are trying to solve exactly? And what's your exact code? (Currently there's no return false in your code for example) \$\endgroup\$ – Simon Forsberg Sep 24 '16 at 20:43
  • \$\begingroup\$ It is a really general occasion. I use it quite often. Just so you understand, for example checking tic tac toe states (though there you have three winning positions to check if they have the same value, while I try to do this for infinite number of positions) \$\endgroup\$ – Кристиян Кацаров Sep 24 '16 at 20:46
  • \$\begingroup\$ I've voted to close because this reads like hypothetical code (where does 'Sample' come from? As far as efficiency goes, it seems like checking for text != "Sample" and returning false would avoid the need to create and append a collection, then just return true if you make it out of the loop. \$\endgroup\$ – forsvarir Sep 24 '16 at 21:23
  • \$\begingroup\$ Yes sample is hypothetical, but it does not matter, the case is to check if all array values are the same in most efficient way... \$\endgroup\$ – Кристиян Кацаров Sep 24 '16 at 21:42

You are iterating over the list, and copying elements that have a certain property to the correct list, then checking whether it's of the size of the original list. In other words, you're checking whether all elements fulfill a certain condition, in other words:

return all(object[number].text == "Sample" for number in array)

I needed to make your example more concrete given your text property description using a list of integers.

array = ["Sample", "Sample", "Sample", "None", "Sample", "Sample"]

If you just need to generate a list of elements with a test for each element or property of that element you can neatly create a list comprehension, roughly relating to your code:

correct = [number for number in array if number is "Sample"]

Which returns:

['Sample', 'Sample', 'Sample', 'Sample', 'Sample']

An else is not included, but you could add one for elements not equal to "Sample". Maybe this could include a check of some sort. I am not sure about efficiency improvements, just a more succinct statement.


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