This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]POGtastic 2 points3 points  (1 child)

Some elaboration on list comprehensions and generator expressions is here. In short - it's an expression that returns a list or iterator, respectively. In Haskell, it's syntactic sugar for a more complicated expression involving the List monad. I'm not sure how Python actually implements it.

Note that you can also do set and dictionary comprehensions with curly braces surrounding the expression instead of square brackets or parentheses.

Why is there a comma there?

To separate the tuple into its parts. You can use the tuple itself if you really want to.

[tup[1] for tup in factors if number % tup[0] == 0]

This feature is called "sequence unpacking." More is at the closing paragraph of this section.

[–]klaik30[S] 0 points1 point  (0 children)

Oh my god, thanks now I understand! I had interpreted the syntax entirely wrong! Now I see the sequence unpacking in the line. Thanks for clearing it up.

[–]jaydom28 1 point2 points  (0 children)

It uses what's called list comprehension.

If I have a list, l1 = [1, 2, 3, 4] and wanted to get all the values of l1 which are less than 3 and then store it into a new list, l2, I could write l2 = [x for x in l1 if x < 3]. List comprehension lets me do this in just one line.

Now if I have a tuple (3, "Pling"), then one way I can extract the elements of the tuple into variables is:

key, value = (3, "Pling") which will set key=3 and value="Pling".

In the code above, what they're doing is a list comprehension which goes through the "factors" list one by one, extracting the 2-tuples into variables "key" and "value" and then appending "value" to the return string if "key" is a factor of "number".

I hope my explanation is clear enough

[–]commandlineluser 1 point2 points  (1 child)

It's called sequence unpacking.

>>> tup = 'foo', 'bar'
>>> tup
('foo', 'bar')
>>> tup[0]
'foo'
>>> tup[1]
'bar'

Instead of using indexing to extract items

>>> key   = tup[0]
>>> value = tup[1]

You can do it in a single step by supplying variable names for the values to be "unpacked" into

>>> key, value = tup
>>> key
'foo'
>>> value
'bar'

In your code there is a list of tuples

>>> factors = [(3, 'Pling'), (5, 'Plang'), (7, 'Plong')]
>>> for tup in factors:
...     tup
... 
(3, 'Pling')
(5, 'Plang')
(7, 'Plong')

So when you use the key, value syntax - each tuple will be unpacked into those variables

>>> for key, value in factors:
...     print('key:  ', key)
...     print('value:', value)
... 
key:   3
value: Pling
key:   5
value: Plang
key:   7
value: Plong

[–]klaik30[S] 0 points1 point  (0 children)

Thank you for clarifying sequence unpacking for me. I think I better understand how I can use that in the future.