Q:

Print list element following a pattern match in Python

I would like to print the preceding element in a list following a pattern match. In the basic example below I match the string 'foo' in a list. I would like to print out not the match itself ('foo') but the following element to the match (in this case 'bar').
theList = ["foo", "bar", "baz", "qurx", "bother"] # example list

list1 = "foo" # matching string

regex = re.compile(list1)

[m.group(0) for l in theList for m in [regex.search(l)] if m] # returns 'foo'

The above code returns the match, but like I said I would like to return the following element in theList. Any help with be greatly appreciated.

A:

Don't try to use clever things like list comprehensions when you are not yet quite sure how they work. It is perfectly OK to use simple code - readable code is easier to verify, after all.
Try this (for clarity I left out the regular expression nonsense):
haystack = ["foo", "bar", "baz", "foo", "qurx", "bother"]
needle = "foo"

result = []
for i, element in enumerate(haystack):
    if needle in element:
        result.append(haystack[i+1])

print(result)

If you are only interested in the first (or only) match, you can use
haystack = ["foo", "bar", "baz", "foo", "qurx", "bother"]
needle = "foo"

for i, element in enumerate(haystack):
    if needle in element:
        print(haystack[i+1])
        break

If you can also match on equality instead of using regex, this is the easiest approach:
idx = haystack.index(needle)
result = haystack[idx+1]

The examples above will all break if the needle is found at the last position of haystack, but I leave that as exercise to the reader.
Properly implementing your original approach, the solution could look something like this:
pairs = zip(haystack, haystack[1:])
[following for matching, following in pairs if needle in matching]

