×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Find the number occurring odd number of times using lambda expression and reduce() function in Python

Learn how to find the number occurring odd number of times using lambda expression and reduce() function in Python?
Submitted by IncludeHelp, on March 14, 2022

Given/input an array of positive integers. We have to find the number which is occurring the odd number of times. All numbers in the list present an even number of times except one (that we have to find).

To find that element – we will use the lambda function and reduce() function. The Lambda function is an anonymous function - that means the function which does not have any name. And, the reduce() function applies to each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.

Example:

Input: 
list1 = [10, 20, 10, 30, 30, 20, 20]

Output:
20

Python code to find the number occurring odd number of times using lambda expression and reduce() function

Define a lambda function and use reduce() function over the list until the single value is left expression reduces the value of x ^ y into single value x starts from 0 and y from 1.

# Importing redecue() function

from functools import reduce

def findElement(list1):
	print (reduce(lambda x, y: x ^ y, list1))

# Main function
if __name__ == "__main__":
	list1 = [10, 20, 10, 30, 30, 20, 20]
	findElement(list1)

Output:

20

Python Lambda Function Programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.