Home > Back-end >  How to do something else at the end of an iteration
How to do something else at the end of an iteration

Time:01-06

I have a list that contains some strings , I want to add some predefined values before every string in a list but the value at the end of the iteration should be different

Here is the list

lst = ['USER_INVITE','USER_LEAVE','GIVEAWAY_START','GIVEAWAY_EDIT','USER_INVITE','USER_LEAVE']

the expected output is

<:878677713269968896:909470525108154399> USER_INVITE
<:878677713269968896:909470525108154399> USER_LEAVE
<:878677713269968896:909470525108154399> GIVEAWAY_START
<:878677713269968896:909470525108154399> GIVEAWAY_EDIT
<:878677713269968896:909470525108154399> USER_INVITE
<:878677686350934027:910454682219085834> USER_LEAVE

here you can see the value before USER_LEAVE is different than others

I can simply do something like this to put these values before strings without a loop

logs = '<:878677713269968896:909470525108154399>\n'.join(map(str,keys[I]))

maybe iteration will help in this case by doing something else at the end of the loop

CodePudding user response:

Using iteration, and some control flow logic around identifying the last item in the list, this can be done as follows:

output_str = ""

for i, item in enumerate(lst):
    if i == len(lst) - 1:  # Logic for identifying the last element
        prefix = '<:878677686350934027:910454682219085834>'
    else:  # If not the last element in the list, do this:
         prefix = '<:878677713269968896:909470525108154399>'
    
    output_str  = f'{prefix} {item}\n'

CodePudding user response:

output_str = ""

for item in lst[:-1]:
    output_str  = f'<:878677686350934027:910454682219085834> {item}\n'
output_str  = f'<:878677713269968896:909470525108154399> {lst[-1]}'

CodePudding user response:

You can just work on every key but the last and then combine the output at the end.

a = "\n".join('<:878677713269968896:909470525108154399>'   key for key in lst[:-1])
b = '<:878677686350934027:910454682219085834>'   lst[-1]
a   b

'<:878677713269968896:909470525108154399>USER_INVITE\n<:878677713269968896:909470525108154399>USER_LEAVE\n<:878677713269968896:909470525108154399>GIVEAWAY_START\n<:878677713269968896:909470525108154399>GIVEAWAY_EDIT\n<:878677713269968896:909470525108154399>USER_INVITE<:878677686350934027:910454682219085834>USER_LEAVE'
  •  Tags:  
  • Related