0

I'm a beginner in Python and trying my hand at using Leetcode & other online resources to learn Python! Recently saw this solution being passed around for longestCommonPrefix on leetcode (thank you hwendy12 !) and was a little curious as how zip(*list) works.

    def longestCommonPrefix(self, strs): 
    """
    :type strs: List[str]
    :rtype: str
    """
        answer = ''
        for i in zip(*strs):
            if len(set(i)) == 1:
                answer += i[0]
            else:
                break
        return answer

I tried searching around and it seems that the * 'unpacks' a list and makes each element a separate argument? I'm a little shaky on how zip works as well and so just wanted to ask what the difference between what zip(list) vs zip(*list) does and what each produces.

Thank you so much!

  • "zip(list) vs zip(*list)" - see the zip documentation. zip with one argument is useless – zvone Jan 05 '21 at 13:04
  • 1
    It's trivial to see for yourself what the results are in a Python shell. `list(zip(["hello", "world"]))` yields `[('hello',), ('world',)]` whereas unpacking `list(zip(*["hello", "world"]))` (which is equivalent to `list(zip("hello", "world"))`) will yield `[('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]`. – Paul M. Jan 05 '21 at 13:05
  • Earlier posts is very helpful, you should read through. If you just give one argument to zip, then you will still get `tuples` results: >>> lst = [1, 2, 3, 4] >>> print(*zip(lst)) (1,) (2,) (3,) (4,) – Daniel Hao Jan 05 '21 at 13:08

0 Answers0