Python Forum
List and string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: List and string (/thread-31016.html)



List and string - emirasal - Nov-18-2020

I have a list something like this:
courses = ['MATH201:A', 'CS222:C', 'IF100:B']

and user enters course name like
coursename = "MATH201"

I just want to find the index of the course that user entered in the list but error message says that "MATH201" is not in the list because "MATH201" is not exactly in the list. How can i find the index of this course without asking from user exactly "MATH201:A"


RE: List and string - DeaD_EyE - Nov-18-2020

You need to check if the pattern is in each element.
To achieve this, you've to iterate (direct or indirect) over the list.

Each element in the list is a str.
You can check each element. The methods startswith and endswith can be used with an if-condition. Str do also support containment checking. You can look if a str is in another str.


courses = ['MATH201:A', 'CS222:C', 'IF100:B']
predicate = "MATH201"
for index, course in enumerate(courses):
    if course.startswith(predicate):
        print(course, "starts with", predicate, "at index", index)
    elif predicate in course:
        print(course, "is contained in", predicate, "at index", index)
# is a generator
# https://wiki.python.org/moin/Generators
def find_all(sequence, predicate):
    for index, element in enumerate(sequence):
        if predicate in element:
            yield index


def find_first(sequence, predicate):
    for first in find_all(sequence, predicate):
        return first


courses = ['MATH201:A', 'CS222:C', 'IF100:B']
predicate = "MATH201"
index = find_first(courses, predicate)
if index is None:
    print(predicate, "was not found.")
else:
    print(predicate, "was found in sequence")
    print("Index:", index)
You can use the previous defined find_all to get more than one result.

courses = ['MATH201:A', 'CS222:C', 'MATH201:B', 'IF100:B', 'MATH201:C']
indices = list(find_all(courses, "MATH"))
You can also use a list comprehension:
courses = ['MATH201:A', 'CS222:C', 'MATH201:B', 'IF100:B', 'MATH201:C']
indicies = [index for index, element in enumerate(courses) if "MATH" in element]
Here are the operations for sequences:
https://docs.python.org/3/library/stdtypes.html#common-sequence-operations

A str is also a sequence. All this operation could be applied on str.
Enumerate: https://docs.python.org/3/library/functions.html#enumerate