Python - Check if a 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 = [427, 789, 345, 122, 471, 124]

print("The list is :")
print(my_list)

my_digits = [1, 4, 7, 2]
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("The list contains the required digits")
else:
   print("The list doesn't contain the required digits")

Output

The list is :
[427, 789, 345, 122, 471, 124]
The list doesn't contain the required digits

Explanation

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

  • Another list of integers is defined.

  • A list comprehension is defined to iterate over the list of integers.

  • The ‘join’ method is used to join the elements.

  • This is assigned to a variable.

  • This is done on the original list as well. Let us call it ‘all_elems’.

  • A variable is assigned to ‘True’/

  • The ‘all_elems’ list is iterated over, and if the element is not present in the previous list, the variable is assigned ‘False’.

  • The execution is also broken.

  • Outside this, if the variable has a value ‘True’, relevant message is defined.

raja
Updated on 16-Sep-2021 07:57:00

Advertisements