0

I'm trying to understand list comprehension in python using this example -

async def on_member_update(before, after):
    stream = [i for i in after.activities if str(i.type) == "ActivityType.streaming"]
    if stream:

The above example is using the api from discord.py. Streaming is a member activity - https://discordpy.readthedocs.io/en/stable/api.html#activity . ActivityType.streaming is a type - https://discordpy.readthedocs.io/en/stable/api.html#discord.ActivityType

What's going on in this loop? I'll try and walkthrough what I may know. So if (i.type) returns as a string then it would be looping through the characters in the stream list? I'm confused. after.activites is the member's CURRENT activity. So it'd be streaming. What exactly does (i.type) represent what how is the loop interacting with after.activites?

Getting lost. Could someone walk me through the steps of what's happening here? Thank you!

  • 2
    "How does this code work?" is generally considered off-topic on this site. You'll likely get better responses to questions like these in the future on https://www.reddit.com/r/learnpython – ddejohn Feb 04 '22 at 18:51
  • 2
    Does https://duckduckgo.com/?q=python+how+does+a+list+comprehension+work help? – Karl Knechtel Feb 04 '22 at 18:51
  • Welcome to Stack Overflow. Please read [ask] and https://stackoverflow.com/help/dont-ask. This is not a tutoring service; we don't deal in explaining the fundamentals of the language or talking through someone else's code. We deal in helping you with the process of *writing your own* code. – Karl Knechtel Feb 04 '22 at 18:54
  • My apologies. Will review the rules – bighelpdiscord Feb 04 '22 at 19:30

1 Answers1

1

List comprehensions can be mechanically transformed into loops. This comprehension is equivalent to the code

stream = []
for i in after.activities:
    if str(i.type) == "ActivityType.streaming":
        stream.append(i)

Unrelated, it is somewhat atypical to compare the type of something by first converting it to a string and then comparing the resulting string. Knowing nothing else, I would expect to see instead the line

    if i.type == ActivityType.streaming

or perhaps a isinstance() instead of direct type comparison if there can be meaningful subtypes.

davidlowryduda
  • 2,404
  • 1
  • 25
  • 29