Find a sequence within a sequence

What is the idiomatic form of locating a sequence within a sequence? e.g. if "bc" in "abcd"True and "abcd".find("bc")1, how do I write ["b", "c"] <in-or-find-like-operator> ["a", "b", "c", "d"]?

One way would be to convert your list objects into string objects:

list_1 = ["a", "b", "c", "d"]
list_2 = ["b", "c"]

str_1 = ''.join(list_1)
str_2 = ''.join(list_2)

… then you can use if str_2 in str_1:

Nice. Thanks.

And… if I had a sequence of integers to locate within a sequence of integers?

Or if had a sequence of other heterogeneous types for which I could still use a == (e.g. [True, 2.0, "b"] == [1, 2, "b"]True), to locate within a longer sequence?

What would be the “Pythonic” way of doing that using built-ins or the standard library?

You’re welcome.

For a list of integers, you could use a similar method, but with list comprehension together with a type conversion:

list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [2, 3, 4]

str_1 = ''.join([str(n) for n in list_1])
str_2 = ''.join([str(n) for n in list_2])

I’d have to have a think about a list the contains mixed types, as I don’t know (off of the top of my head) how you’d do that in a simple way.

To add: the only way I can think of (for list objects that contain mixed types) is to again convert the items into the same type, i.e a type string.

Here’s the simplest way I can think of.

sequence = [1, 2, 3, 4, 5]
subsequence = [3, 4]

print(any(sequence[i: i + len(subsequence)] == subsequence for i in range(len(sequence) - len(subsequence) + 1)))
1 Like

You may want to have a look at some of the popular string searching algorithms (eg String-searching algorithm - Wikipedia ) to see if they can be adapted. Otherwise, a naive approach may well be sufficient, depending on how large your search list is.