Search code examples
python-3.xlisttuplesdata-conversion

Simple Syntax Question (tuple conversion)


I'm currently researching different ways to combine, organize and manipulate data for different purposes.

Just today I found this zip() / iter() technique of creating a LIST containing TUPLES while also being able to specify how many elements are in each TUPLE. However, I'm unable to fully understand part of the syntax.

Here is the code:

mylist = [1,2,3,4,5,6]

converted = [x for x in zip(*[iter(mylist)]*2)]

print(converted)

This is the output (which is what I want):

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

What I'm trying to grasp is the first asterisk. I understand that it's most likely in relation to the '*2' telling the 'iter' or 'zip' function how many elements each tuple should contain, however, I'm trying to grasp the need for it's placement.

Any help is greatly appreciated.

Also, if you know of another technique to accomplish this and feel like sharing, I'd greatly appreciate learning from you.

Thanks again in advance guys!


Solution

  • Basically iter(mylist) makes an iterator object for the list, then it's put into a list [iter(mylist)] which is multiplied by 2 basically making a list that contains two references to the same iterator object: [iter(mylist)]*2 -> [<list_iterator object at 0x7f8fbc1ac610>, <list_iterator object at 0x7f8fbc1ac610>]

    The first asterisk unpacks the list as arguments into the zip() function. To make it easier to understand as I'm not very good at explaining things, this code does the same as yours:

    mylist = [1,2,3,4,5,6]
    
    iterators = [iter(mylist)] * 2
    converted = [x for x in zip(*iterators)]
    
    print(converted)
    

    So it makes an iterator, then it makes a list that contains two references to the same iterator object by multiplying it by 2. And then it unpacks the list to be used as arguments for the zip() function

    I hope this cleared it up at least a little for you as I'm not very good at explaining.