Here's a fun one:
l = ['nomad', 'normal', 'nonstop', 'noob']
def common_prefix(lst):
for s in zip(*lst):
if len(set(s)) == 1:
yield s[0]
else:
return
result = ''.join(common_prefix(l))
Result:
'no'
To answer the spirit of your question - zip(*lst)
is what allows you to "iterate letters in every string in the list at the same time". For example, list(zip(*lst))
would look like this:
[('n', 'n', 'n', 'n'), ('o', 'o', 'o', 'o'), ('m', 'r', 'n', 'o'), ('a', 'm', 's', 'b')]
Now all you need to do is find out the common elements, i.e. the len
of set
for each group, and if they're common (len(set(s)) == 1
) then join it back.
As an aside, you probably don't want to call your list by the name list
. Any time you call list()
afterwards is gonna be a headache. It's bad practice to shadow built-in keywords.