Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Compare List of Dictionaries in Python
Next article icon

How to Compare Adjacent Elements in a List in Python

Last Updated : 14 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To compare adjacent elements in a list, we iterate through the list and compare each element with the next one to check if consecutive elements are equal or meet specific conditions.

Using the itertools.pairwise()

This is an efficient way to iterate through adjacent pairs. It generates consecutive pairs (a, b) from the input iterable without creating additional intermediate lists, making it both memory-efficient and fast.

Python
li = [1, 2, 2, 3, 4, 4, 5]   # Loop through indices of the list for i in range(len(li) - 1):        a = li[i]  # current element     b = li[i + 1] # next element          print(a, b, " ", a == b) 

Output
1 2   False 2 2   True 2 3   False 3 4   False 4 4   True 4 5   False 

Explanation:

  • range(len(li) - 1) : This generates indices from 0 to len(li) - 2 and ensures the loop stops at the second-to-last element.
  • print(a, b, " ", a == b):This prints the current element a , next element b, a space and whether a is equal to b.

Using zip()

zip() function in Python is a efficient tool for pairing elements from two or more iterables, such as lists. By combining the original list with a sliced version of itself . It pairs adjacent elements together, making it an ideal choice for tasks like comparing adjacent elements in a list.

Python
li = [1, 2, 2, 3, 4, 4, 5]  for a, b in zip(li, li[1:]):     print(a, b, " ", a == b) 

Output
1 2   False 2 2   True 2 3   False 3 4   False 4 4   True 4 5   False 

Explanation: zip(li, li[1:]) pairs each element of the list li with the next element by combining the original list li and its sliced version li[1:] .

Using List Comprehension

By using a single line of code, list comprehension generates a new list that holds tuples, where each tuple consists of the current element, the next element and the result of their comparison.

Python
li = [1, 2, 2, 3, 4, 4, 5]  # compare adjacent elements res = [(li[i], li[i + 1], li[i] == li[i + 1]) for i in range(len(li) - 1)]  # Print result for r in res:     print(r[0], r[1], " ", r[2]) 

Output
1 2   False 2 2   True 2 3   False 3 4   False 4 4   True 4 5   False 

Explanation:

  • list comprehension: This iterates through the list li, pairing each element li[i] with the next element li[i + 1] and compares whether they are equal, storing the result as True or False in a tuple.
  • for r in res: This iterates through each tuple in the list and prints the elements alongside the comparison result .

Using loops

Using loops , we can manually iterate through a list and compare adjacent elements by accessing each element and its next neighbor. This approach requires explicit control over the loop indices, but it can become inefficient for larger lists due to redundant operations.

Python
li = [1, 2, 2, 3, 4, 4, 5]  # compare adjacent elements for i in range(len(li) - 1):     a = li[i]     b = li[i + 1]     print(a, b, " ", a == b) 

Output
1 2   False 2 2   True 2 3   False 3 4   False 4 4   True 4 5   False 

Explanation: for i in range(len(li) - 1) loop iterates over the indices of the list li, stopping at the second-to-last element (len(li) - 1). This ensures that each element is compared with the next one without going out of bounds.


Next Article
How to Compare List of Dictionaries in Python

V

vishuvaishnav3001
Improve
Article Tags :
  • Python
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • Check if element exists in list in Python
    In this article, we will explore various methods to check if element exists in list in Python. The simplest way to check for the presence of an element in a list is using the in Keyword. Example: [GFGTABS] Python a = [10, 20, 30, 40, 50] # Check if 30 exists in the list if 30 in a: print("Eleme
    3 min read
  • Python | Consecutive elements grouping in list
    Sometimes, while working with Python lists, we can have a problem in which we might need to group the list elements on basis of their respective consecutiveness. This kind of problem can occur while data handling. Let's discuss certain way in which this task can be performed. Method 1: Using enumera
    5 min read
  • Compare two Files line by line in Python
    In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation.
    3 min read
  • Python - Count the elements in a list until an element is a Tuple
    The problem involves a list of elements, we need to count how many elements appear before the first occurrence of a tuple. If no tuple is found in the list, return the total number of elements in the list. To solve this, initialize a counter and use a while loop to iterate through the list, checking
    2 min read
  • How to Compare List of Dictionaries in Python
    Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
    3 min read
  • Break a list comprehension Python
    Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to in
    2 min read
  • Python - Check if list contains all unique elements
    To check if a list contains all unique elements in Python, we can compare the length of the list with the length of a set created from the list. A set automatically removes duplicates, so if the lengths match, the list contains all unique elements. Python provides several ways to check if all elemen
    2 min read
  • Check if two lists are identical in Python
    Our task is to check if two lists are identical or not. By "identical", we mean that the lists contain the same elements in the same order. The simplest way to check if two lists are identical using the equality operator (==). Using Equality Operator (==)The easiest way to check if two lists are ide
    2 min read
  • How to Skip a Value in a List in Python
    Skipping a value in a list means we want to exclude certain items while iterating. There are many ways to skip a value in Python List. Using continue is the simplest way to skip a value in iteration, without modifying the original list. [GFGTABS] Python a = [1, 2, 3, 4, 5] # iterating the list for i
    2 min read
  • How to compare two text files in python?
    Python has provided the methods to manipulate files that too in a very concise manner. In this article we are going to discuss one of the applications of the Python's file handling features i.e. the comparison of files. Files in use: Text File 1Text File 2Method 1: Comparing complete file at once Py
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences