-2
list1 = ['A', 'C', 'G', 'T']

a = input("Please enter your gene sequence: ")

Let's say the user enter "GTCAACTB". How can I check each letter in a to make sure that it is in list1 and if not, ask the user to input again? I don't know how to check the entire input against the list.

In brief, I want to check if the sequence of letters from the input are in list1. The sequence could one letter or a sequence of 20 letters

reevesv2
  • 1
  • 1
  • 1
    Does this answer your question? [How to check if a string contains an element from a list in Python](https://stackoverflow.com/questions/6531482/how-to-check-if-a-string-contains-an-element-from-a-list-in-python) – tgikal Apr 14 '20 at 18:24

1 Answers1

2

Something like this:

list1 = ['A', 'C', 'G', 'T']

repeat = True
while repeat:
    a = input("Please enter your gene sequence: ")
    repeat = any([char.upper() not in list1 for char in a])

This [char.upper() not in list1 for char in a] is known as list comprehension in Python and allows you to create a new list by iterating over the characters in your string a. The value added for each character in a is char.upper() not in list1 which is a boolean value, checking if that character does not exist in list1. At the end you should have a new list [False, True, False] and using any() higher-order function you check if in that list there is any (at least one) True value (i.e., if there is at least one True value it means there is a character in the string that is not in list1).

For a = "ABC" the list comprehension [char.upper() not in list1 for char in a] yields to [False, True, False] and any([False, True, False]) = True.

Rafael
  • 7,002
  • 5
  • 43
  • 52