Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding return [0,size-1][nums[0]<nums[size-1]] in Python

Tags:

python

list

While working on a simple coding question, writing a function findPeakElement, I came across the following code:

def findPeakElement(self, nums):
     size = len(nums)
     for x in range(1,size-1):
         if nums[x] > nums[x-1] and nums[x] > nums[x+1]:
            return x

     return [0,size-1][nums[0]<nums[size-1]]

What is the meaning of last line?

like image 248
Glorious Manutd Avatar asked May 08 '19 04:05

Glorious Manutd


People also ask

What is the meaning of [:- 1 in python?

In Python, [::-1] means reversing a string, list, or any iterable with an ordering. For example: hello = "Hello world" nums = [1, 2, 3, 4] print(hello[::-1])

What does %% mean in Python?

When you see the % symbol, you may think "percent". But in Python, as well as most other programming languages, it means something different. The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand.

What does this mean in Python [: 0?

edited Nov 27, 2020 by hari_sh. It acts as an indicator in the format method that if you want it to be replaced by the first parameter(index zero) of format. Example : print(42+261={0}.format(303)) Here, {0} will be replaced by 303.

What does [:: 4 mean in Python?

string[::4] reads “default start index, default stop index, step size is four—take every fourth element“. string[2::2] reads “start index of two, default stop index, step size is two—take every second element starting from index 2“.


1 Answers

That last row is an obscure way of writing an if then else expression.

  • [0, size-1] creates a list of two elements.
  • nums[0] < nums[size-1] returns either True or False
  • when used as a list index, this True/False is implicitly converted into 1 or 0.
  • and by that, either size-1 or 0 is picked from the list.

A clearer way to write it is:

return size - 1 if nums[0] < nums[size - 1] else 0
like image 73
Roland Illig Avatar answered Oct 15 '22 09:10

Roland Illig