Home » Python » Python programs

Check all elements of a list are the same or not in Python

Here, we are going to learn how to check all elements of a list are the same or not in Python programming language?
Submitted by IncludeHelp, on March 27, 2020

Here, we are implementing a python program to check whether all elements of a list are the same or not?

We can use [1:] and [:-1] to compare all the elements in the given list.

Program:

# function to check elements
def check_equal(a):
  return a[1:] == a[:-1]

# lists
x = [10, 20, 30, 40,50]
y = [10, 20, 20, 20, 20]
z = [10, 10, 10, 10, 10]

# check how [1:] and [:-1] wors?
print("x: ", x)
print("x[1:]: ", x[1:])
print("x[:-1]: ", x[:-1])
print("check_equal(x): ",check_equal(x))
print()

print("y: ", y)
print("y[1:]: ", y[1:])
print("y[:-1]: ", y[:-1])
print("check_equal(y): ",check_equal(y))
print()

print("z: ", z)
print("z[1:]: ", z[1:])
print("z[:-1]: ", z[:-1])
print("check_equal(z): ",check_equal(z))
print()

Output

x:  [10, 20, 30, 40, 50]
x[1:]:  [20, 30, 40, 50]
x[:-1]:  [10, 20, 30, 40]
check_equal(x):  False

y:  [10, 20, 20, 20, 20]
y[1:]:  [20, 20, 20, 20]
y[:-1]:  [10, 20, 20, 20]
check_equal(y):  False

z:  [10, 10, 10, 10, 10]
z[1:]:  [10, 10, 10, 10]
z[:-1]:  [10, 10, 10, 10]
check_equal(z):  True






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.