Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[] vs *[]
#1
Hey guys

what the different between sending a send as [] and *[]? For instance

def main():
    x = [1] * 10
    print(list(chain(*x)))
    print(list(chain(x)))
Error:
Traceback (most recent call last): File "/home/harish/hshivaraj/source/python/leetcode/2022/BAM/itertools_exp.py", line 8, in <module> main() File "/home/harish/hshivaraj/source/python/leetcode/2022/BAM/itertools_exp.py", line 6, in main print(list(chain(*x))) TypeError: 'int' object is not iterable
Calling first method with chain(*x) return a generator and when I pass the generator to list() it fails. does anyone have an explanation?

thanks
Reply
#2
itertools.chain() expects that all of its arguments are iterable. So you can hand it a list and it can iterate over it.

When you call chain(x), the function is handed the list and can iterate to get the elements inside.
When you call chain(*x), the caller unpacks the elements itself. This turns into chain(1, 1, 1, 1, 1, 1, 1, 1, 1, 1).

Now the first argument (an integer) is not iterable. When you operate on the generator that chain() produced, it discovers this and throws an exception.

Docs:
Quote:An asterisk * denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
Reply
#3
Thanks vert much bowlofred. That does clearly explains the reasons behind the error.

I also noticed a small performance differences between unpacking vs sending the list. To my surprise unpacking performed better than sending the list. Which really surprised me. Do you know why that might be?
Reply
#4
Post your timing code. What are you comparing unpacking against?
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020