Python - Check if list contain particular digits

PythonServer Side ProgrammingProgramming

When it is required to check if a list contains particular digits, the ‘join’ method, and a simple iteration are used.

Example

Below is a demonstration of the same

my_list = [415, 133, 145, 451, 154]

print("The list is :")
print(my_list)
my_digits = [1, 4, 5, 3]

digit_string = ''.join([str(ele) for ele in my_digits])
all_elems = ''.join([str(ele) for ele in my_list])

my_result = True
for element in all_elems:

   for ele in element:
      if ele not in digit_string:
         my_result = False
         break

if(my_result == True):
   print("All elements have been made from required digits")
else:
   print("All elements haven't been made from required digits")

Output

The list is :
[415, 133, 145, 451, 154]
All elements have been made from required digits

Explanation

  • A list is defined and is displayed on the console.

  • Another list with integers is defined.

  • The list comprehension is used to iteated through the second list, and join them.

  • This is assigned to a variable.

  • Another list comprehension is used to iterate over the first list and join them.

  • This is assigned to another variable.

  • Another result variable is initially assigned to ‘True’.

  • The second variable is iterated over, and if it is not found in the first variable, the result variable is assigned to ‘False’.

  • If result is still ‘True’ after coming out of the condition, relevant message is displayed on the console.

raja
Updated on 15-Sep-2021 11:49:55

Advertisements