1

I have this code in Python where i have to print the non repetitive alphabets in below list. like the output should be 'fl' since 'fl' is common in all the three string:

x=["flower","flow","flight"]

print([i for i in zip(*x)])

It prints the following output:

[('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]

How does it work? I know that zip(*) is used to unzip a list. is it taking "flower,"flow" and "flight" as separate list items.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Micky
  • 55
  • 6
  • The zip will take only the length of the lists which is common to all. In this case, only the 4 characters from each string because the smallest string is `flow` with 4 characters – Sheldore May 03 '19 at 23:07
  • You will get the same result with `print([*zip(*x)])` – Mykola Zotko May 04 '19 at 08:21

2 Answers2

2

zip works with any kind of iterable type. While it's most often used with lists, any iterable will work. Strings are iterable, and each iteration returns the next character in the string.

So iterating over a string like "flower" is the same as iterating over the list ["f", "l", "o", "w", "e", "r"]. Thus, when you zip several strings, it groups the corresponding characters, just as when you zip over similar lists.

Writing zip(*x) makes use of argument unpacking. Each element of x becomes a separate argument to zip. So it's equivalent to writing:

zip(x[0], x[1], x[2])

which is equivalent to:

zip("flower", "flow", "flight")

The final result only has 4 elements because zip stops when it gets to the end of the shortest input, which is "flow" in this case.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

After Barmars answer explaining how zip and * work (see. f.e. Zip lists in Python and Unpack a list in Python? for more informations) you still lack part of your question answered:

How to print the "common" letters of your input:

x = ["flower","flow","flight"]
zipped = zip(*x)

for a,b,c in zipped:
    if a == b == c:
        print(a, end = "")
    # do nothing if the 3 elements are not equal

Output:

fl

You can also use a comprehension inside join to get this output:

# take k[0] if all elements of k are equal, apply for all k in zipped
print( ''.join(k[0] for k in zipped if k[0]==k[1]==k[2]))

Doku:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69