Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check if last value of list occurs more than once

Tags:

python

list

Problem:

Write a program that will search through a list to see if the last value in the list occurs more than once. If the last value occurs more than once, return true. Otherwise, return false. If the list is empty, return false.

My Code:

def go(list1):
for i in range(0,len(list1)):
    if list1[i] is list1[-1:]:
        return True
else:
    return False

print ( go( [-99,1,2,3,4,5,6,7,8,9,10,5] ) )
print ( go( [10,9,8,7,6,5,4,3,2,1,9] ) )
print ( go( [10,20,30,40,50,-11818,40,30,20,10] ) )
print ( go( [32767] ) )
print ( go( [7,7,7,7] ) )
print ( go( [9,10,-88,100,-555,1000] ) )
print ( go( [10,10,10,11,456,10,10] ) )
print ( go( [-111,1,2,3,9,11,20,30] ) )
print ( go( [9,8,7,6,5,4,3,2,0,-2,9,9] ) )
print ( go( [12,15,18,21,23,1000] ) )
print ( go( [250,19,17,15,13,11,10,9,6,3,2,1,250] ) )
print ( go( [] ) )

My Output:

False
False
False
False
False
False
False
False
False
False
False
False

Desired Output:

True
True
True
False
True
False
True
False
True
False
True
False

What am I doing wrong? Why am I getting False for all my outputs?

like image 405
JenkinsMa Avatar asked Dec 08 '25 06:12

JenkinsMa


2 Answers

You should not be using is here, because is does not check for equality of values, but instead for equality of references.

Instead you can use arr[-1] in arr[:-1] to see if the final value of your list is present anywhere else in the list.

x = [-99,1,2,3,4,5,6,7,8,9,10,5] 

def is_last_contained(arr):
  return arr[-1] in arr[:-1]

print(is_last_contained(x))

Output:

True
like image 163
user3483203 Avatar answered Dec 09 '25 21:12

user3483203


There are a couple errors in your code as written:

  1. range(0,len(list1)) should be range(0,len(list1)-1) since you don't want to compare the last element against itself.
  2. list1[-1:] should be list1[-1]. The former selects a slice, the latter a single element.

That being said, @chrisz's solution is more Pythonic and concise :)

like image 25
sushain97 Avatar answered Dec 09 '25 19:12

sushain97



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!