+ 3

Python, product from itertools, and asterisk. I need your help to understand!

# regarding the command, product, and lists, I noticed something that I need help to understand. from itertools import product astr = "SoloLearn Learning LearningIsFun Learnable" alist = astr.split() for i in product(alist): print(i) for i in product(*alist): print(i) """ except asterisk, ('SoloLearn',) ('Learning',) ('LearningIsFun',) ('Learnable',), it just shows each element of list. However, with asterisk, it presents ...('n', 'i', 'I', 'r') ('n', 'i', 'I', 'n') ('n', 'i', 'I', 'a' )('n', 'i', 'I', 'b') ('n', 'i', 'I', 'l') ('n', 'i', 'I', 'e') ('n', 'i', 's', 'L') ('n', 'i', 's', 'e')... basically products of each character of each element attached to other characters from other elements in the list. And I want to know why it differs with such a small difference, which is just " * ". Thanks in advance and I do appreciate your effort to resolve my curiosity!

22nd Apr 2022, 8:54 PM
OTTER
OTTER - avatar
4 odpowiedzi
+ 4
The asterisk, *, or unpacking operator, unpacks list, and passes the values, or elements, of list as separate arguments to the product function. So product(*["123", "abc"]) returns iterator ((x, y) for x in "123" for y in "abc") (1,a), (1,b), (1,c), (2,a), (2,b), (2,c), (3,a), (3,b), (3,c) when product(["123", "abc"]) with the same list without the asterisk, *, returns iterator (x for x in ["123", "abc"])
22nd Apr 2022, 10:45 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 3
just saying some words about itertools product() this function is done for creating the cartesian product. to accomplish this we need at least 2 (or more) iterables. (the initial post is showing a sample with just 1 list) from itertools import product lst1 = [1,2,3] lst2 = 'yes' print(list(product(lst1, lst2))) # res: [(1, 'y'), (1, 'e'), (1, 's'), (2, 'y'), (2, 'e'), (2, 's'), (3, 'y'), (3, 'e'), (3, 's')]
24th Apr 2022, 6:01 PM
Lothar
Lothar - avatar
22nd Apr 2022, 10:39 PM
Simon Sauter
Simon Sauter - avatar
- 1
Have you tried using print? print(alist) print(*alist) and look at the difference.
22nd Apr 2022, 10:37 PM
Slick
Slick - avatar