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:
Python - Test rear digit match in all list elements
Next article icon

Python – Match Kth number digit in list elements

Last Updated : 10 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes we may face a problem in which we need to find a list if it contains numbers at the Kth index with the same digits. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. 

Method #1 : Using list comprehension + map() 

We can approach this problem by converting the elements to the strings and then testing the Kth element of the string and if they are equal we can return true and then convert to set and test for the size of the result to be one. The conversion is done by map, the set function converts to set and list comprehension checks for the Kth element of the string.

Python3




# Python3 code to demonstrate
# Kth Number digit match
# using list comprehension + map()
 
# initializing list
test_list = [467, 565, 2645, 8668]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = 1
 
# using list comprehension + map()
# Kth Number digit match
res = len(set(sub[K] for sub in map(str, test_list))) == 1
 
# Printing the  result
print("Does each element of index K have same digit ? " + str(res))
 
 
Output : 
The original list : [467, 565, 2645, 8668] Does each element of index K have same digit ? True

Time complexity: O(n), where n is the length of the list ‘test_list’.
Auxiliary space: O(n), where n is the length of the list ‘test_list’.

Method #2 : Using all() + list comprehension

This is yet another approach in which this problem can be solved. In this we use all functions to check for all elements and return a Boolean result and list comprehension does the part of the conversion of string by str function and checking for all elements with the Kth digit of Kth element. 

Python3




# Python3 code to demonstrate
# Kth Number digit match
# using list comprehension + all()
 
# initializing list
test_list = [467, 565, 2645, 8668]
 
# Printing original list
print(& quot
       The original list : & quot
       + str(test_list))
 
# Initializing K
K = 1
 
# using list comprehension + all() method
# Kth Number digit match
res = all(str(i)[K] == str(test_list[K])[K] for i in test_list)
 
# print result
print(& quot
       Does each element of index K have same digit ? & quot
       + str(res))
 
 
Output : 
The original list : [467, 565, 2645, 8668] Does each element of index K have same digit ? True

Time complexity: O(n), where n is the length of the test_list. 
Auxiliary Space: O(1), constant extra space is required.

Method #3: Using for loop and len() method

Python3




# Python3 code to demonstrate
# Kth Number digit match
 
# initializing list
test_list = [467, 565, 2645, 8668]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K
K = 1
res = False
x = []
for i in test_list:
    a = str(i)
    x.append(int(a[K]))
y = [x[0]]*len(x)
if(y == x):
    res = True
# print result
print("Does each element of index K have same digit ? " + str(res))
 
 
Output
The original list : [467, 565, 2645, 8668] Does each element of index K have same digit ? True

Time Complexity: O(n), where n is the length of the input list. This is because we’re using loop + len() method which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), as we’re using constant additional space 

Method #4 : Using reduce() and lambda

Python3




# Python3 code to demonstrate
# Kth Number digit match
# using reduce() and lambda
 
# Importing reduce module
from functools import reduce
 
# initializing list
test_list = [467, 565, 2645, 8668]
 
# Printing original list
print("The original list : " + str(test_list))
 
# Initializing K
K = 1
 
# using reduce() and lambda
# Kth Number digit match
res = reduce(lambda x, y: x and (str(y)[K] == str(test_list[K])[K]), test_list)
 
# Printing result
print("Does each element of index K have same digit ? " + str(res))
 
# This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original list : [467, 565, 2645, 8668] Does each element of index K have same digit ? True

This method uses the reduce() function with a lambda function to check if all the Kth digits of the elements in the input list are the same. The lambda function compares the Kth digit of each element to the Kth digit of the first element in the input list.

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #5: Using Recursion

Step-by-step approach:

  • Define a function `check_kth_digit()` that takes `test_list` and `K` as inputs.
  • Check if the length of `test_list` is 0, if yes, return True as all elements have the same digit at index K.
  • Otherwise, convert the first element of `test_list` to a string and extract the Kth digit.
  • Loop through all other elements in `test_list` and compare their Kth digit with the extracted Kth digit from the first element.
  • If any mismatch is found, return False as not all elements have the same digit at index K.
  • If no mismatch is found, call `check_kth_digit()` recursively on the remaining elements of `test_list` (excluding the first element).
  • Return the result of the recursive call.

Python3




def check_kth_digit(test_list, K):
 
    if len(test_list) == 0:  # base case
        return True
    else:
       
        a = str(test_list[0])
        x = int(a[K])
        for i in test_list:
            a = str(i)
            if int(a[K]) != x:
                return False
               
        # Recursive call
        return True and check_kth_digit(test_list[1:], K)
 
 
# Initializing list
test_list = [467, 565, 2645, 8668]
 
# Printing original list
print("The original list : " + str(test_list))
 
# Initializing K
K = 1
 
# Checking if each element of index K has the same digit
res = check_kth_digit(test_list, K)
 
# Printing the result
print("Does each element of index K have the same digit? " + str(res))
 
 
Output
The original list : [467, 565, 2645, 8668] Does each element of index K have the same digit? True

Time complexity: O(N*M), where N is the number of elements in `test_list` and M is the maximum number of digits in an element of `test_list`. This is because we need to loop through each element of `test_list` and extract the Kth digit, which takes O(M) time, and we do this for N elements.

Auxiliary Space: O(M), as we are storing the extracted Kth digit in a variable. Note that the space complexity could be higher if the input elements in `test_list` are very large and require a significant amount of memory for string conversion and storage of digits.

Method #6: Using a set

Step-by-step approach:

  • Initialize a set named “digits” to store the digits present in the Kth position of each element of the list.
  • Loop through the elements of the list.
  • Convert the current element to a string and extract the Kth digit using string indexing.
  • Add the extracted digit to the “digits” set.
  • Check if the length of the “digits” set is 1. If yes, return True, else return False.

Python3




def check_kth_digit(test_list, K):
    digits = set()
    for num in test_list:
        digit = str(num)[K]
        digits.add(digit)
    return len(digits) == 1
 
 
# Initializing list
test_list = [467, 565, 2645, 8668]
 
# Printing original list
print("The original list : " + str(test_list))
 
# Initializing K
K = 1
 
# Checking if each element of index K has the same digit
res = check_kth_digit(test_list, K)
 
# Printing the result
print("Does each element of index K have the same digit? " + str(res))
 
 
Output
The original list : [467, 565, 2645, 8668] Does each element of index K have the same digit? True

Time complexity: O(n*k), where n is the length of the list and k is the number of digits in each element.
Auxiliary space: O(k), for storing the digits in the set.



Next Article
Python - Test rear digit match in all list elements
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
Practice Tags :
  • python

Similar Reads

  • Python - Test rear digit match in all list elements
    Sometimes we may face a problem in which we need to find a list if it contains numbers ending with the same digits. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1: Using list comprehension + map() We can app
    6 min read
  • Python - List Elements with given digit
    Given list of elements and a digit K, extract all the numbers which contain K digit. Input : test_list = [56, 72, 875, 9, 173], K = 5 Output : [56, 875] Explanation : 56 and 875 has "5" as digit, hence extracted. Input : test_list = [56, 72, 875, 9, 173], K = 4 Output : [] Explanation : No number ha
    6 min read
  • Sum of number digits in List in Python
    Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Python’s built-in functions like sum(), map(), and list comprehensions. For exa
    2 min read
  • Python | Every Kth element in list
    Sometimes, while working with Python lists, we can have a problem in which we require to extract every Kth element of list and slice out a new list from that. This type of problems are quite common as a variation of list slicing. Let's discuss a way in which this can be done. Method : Using list sli
    3 min read
  • Python - First Even Number in List
    Sometimes, while working with lists, we can have a problem in which we need to extract certain numbers occurring first time. This can also be even number. This kind of problem is common in day-day and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 :
    4 min read
  • Python - Sort by Maximum digit in Element
    Given a List of Elements, sort by the maximum digit of the element present in the List. Input : test_list = [234, 92, 8, 721] Output : [234, 721, 8, 92] Explanation : 4 < 7 < 8 < 9, sorted by maximum digits. Input : test_list = [92, 8, 721] Output : [721, 8, 92] Explanation : 7 < 8 <
    6 min read
  • Python | Operate on every Kth element of list
    We generally wish to employ a particular function to all the elements in a list. But sometimes, according to the requirement, we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Let's discuss certain ways in which this can be pe
    5 min read
  • Python | Find closest number to k in given list
    Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K. Examples: Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1 Output : 9.35 Input : lst = [9, 11, 5, 3, 25, 18], K = 6 Output : 5 Method
    5 min read
  • Python - Every Kth index Maximum in List
    We generally wish to employ a particular function to all the elements in a list. But sometimes, according to requirement we would wish to employ a particular functionality to certain elements of the list, basically to every Kth element in list. Let’s discuss certain ways in which maximum of these el
    4 min read
  • Python | Get elements till particular element in list
    Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let's discuss certain ways in
    7 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