Python operator:single star(*)

Posted on February 9, 2019
  • with Zip

    Read a block of pseudo Python code like

    comA = zip(lsA, lsB)
    comB = zip(*comA)

    then made a try to see how * works:

    1
    2
    3
    4
    5
    6
    7
    8
    
    a = [1, 2, 3]
    b = [4, 5, 6]
    c = zip(a,b)
    for j in c:
    print(j)
    d = zip(*c)
    for i in d:
    print(i)

    and the output:

    (1, 4)
    (2, 5)
    (3, 6)

    There is nothing was outputted by line8: print(i), but it works after removing line4-5:

    a = [1, 2, 3]
    b = [4, 5, 6]
    c = zip(a,b)
    d = zip(*c)
    for i in d:
    print(i)

    with the output:

    1, 2, 3)
    (4, 5, 6)

    Just as it was mentioned in the Python doc:

    zip() in conjunction with the * operator can be used to unzip a list

    But I’m still wondering why the first try failed, submitted a question on Stackoverflow: Why “for” affects another zip object? after my debugging, and got the answer shortly: zip variable empty after first use:

    In Python2.x, zip returned a list of tuples

    In Python3, a lot of the builtin functions now return iterators rather than lists (map, zip, filter)

  • List comprehensions: the type of elements is list

    Updated @ 25/Aug/2019

    a = [[1,2], [3,4], [5, 6, 7]]
    c  = [ [*i, sum(i)] for i in a]
    print(c)

    Output:

    [[1, 2, 3], [3, 4, 7], [5, 6, 7, 18]]

Python operator:single star(*)


donation

Scan the QR code using WeChat

comments powered by Disqus