Home > Back-end >  Is there a way to have more relevent variable names in a loop?
Is there a way to have more relevent variable names in a loop?

Time:05-19

I have a list that follows the format :

message = [sender, receiver, message_name]

I have to loop through all my messages stored in my message_stack list and assess for each message whether it's name is valid (i.e if its name is in the valid_names list)

For the moment I have :

for message in message_stack:
    if message[2] not in valid_names:
        print("Error : wrong name.")

The iterator message has a relevant name but is there a way to make message[2] a bit clearer regarding the face that it is a message name ?

Thanks !

CodePudding user response:

You want to use iterable unpacking:

for sender, receiver, message_name in message_stack:
    if message_name not in valid_names:
        print("Error : wrong name.")
    # do some more stuff with sender, receiver....

Terminology note, message is not the "iterator". Iterator has a specific meaning in Python (that which is returned from iter when you do iter(iterable), i.e. iterator = iter(iterable)). You might call it the "loop variable"

CodePudding user response:

You can use:

for sender, receiver, message_name in message_stack:
    if message_name not in valid_names:
        print("Error : wrong name.")

You can even omit sender and receiver if you won't be using them:

for _, __, message_name in message_stack:
    if message_name not in valid_names:
        print("Error : wrong name.")

CodePudding user response:

Use star unpack to get last element:

for *_, message_name in message_stack:
    if message_name not in valid_names:
        print(some_thing)

Or consider using namedtuple when creating lists:

from collections import namedtuple
Message = namedtuple('Message', ['sender', 'receiver', 'name'])
message_stack = # a list of Message object
for message in message_stack:
    if message.name not in valid_names:
        print(some_thing)
  • Related