Search code examples
pythonlistzip

Why does zip() of list of lists output such?


Let's take:

a = zip([[1,2],[2,3]])

where a is the zipped variable of list of lists [[1,2],[2,3]] the output for print(list(a))is

[([1, 2],), ([2, 3],)]

meaning the zip was a tuple containing ([1, 2],), ([2, 3],)? Why is that? For example, why is there a comma before both end parentheses of the tuple?

If someone could walk me through the computational steps I would greatly appreciate it.


Solution

  • "The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and return it."

    Basically it mean that you can do sometime like that:

    list1 = [1,2,3,4]
    list2 = ["h", "b", "s"]
    
    for num, char in zip(list1, list2):
        print(num, char)
    
    # output:
    # 1 h
    # 2 b
    # 3 s
    

    enter value: [[1,2],[2,3]]

    first you zip the list: ([1, 2],), ([2, 3],) or just make tuples to the values

    if you just enter a one list:

    a = zip([1,2,3,4,5,6])
    
    print(list(a))  # [(1,), (2,), (3,), (4,), (5,), (6,)]
    

    it make the values in the list a tuples. (, for make it a one value tuple)

    and after that you make it a list: [([1, 2],), ([2, 3],)]