0

I am trying to set an iterable element for a nested loop which purpose for the first iterable element is to print('just a test'), and for others print a concatenated string.

Here's the attempt:

states=['Alabama', 'Georgia']
titles=['president', 'secretary']
codes=['A80', 'A81']

for index, state in enumerate(states, start=0):
   for index, title in enumerate(titles, start=0):
        for index, code in enumerate(codes, start=0):
             if index==0:
                 print('just a test')
             else:
                 print(state +'-'+title+'-'+code) 

Which returns:

#just a test
#Alabama-president-A81
#just a test
#Alabama-secretary-A81
#just a test
#Georgia-president-A81
#just a test
#Georgia-secretary-A81

Expected output:

#this is a test
#A81-president-Alabama
#A80-secretary-Alabama
#A81-secretary-Alabama
#A80-president-Georgia
#A81-president-Georgia
#A80-secretary-Georgia
#A81-secretary-Georgia

How could I rename the iterable element?

AlSub
  • 1,384
  • 1
  • 14
  • 33
  • 1
    You can use `enumerate` and test if the current index equals `0`. – Christian Dean Apr 07 '21 at 17:38
  • 1
    Also see [this](https://stackoverflow.com/questions/45621722/im-getting-an-indentationerror-how-do-i-fix-it) regarding the syntax error. – Christian Dean Apr 07 '21 at 17:39
  • Do you mean something like `for state in enumerate(states)`? – AlSub Apr 07 '21 at 18:00
  • Not quite. `enumerate` produces tuples, so you need to separate the index and actual list value: `for index, value in enumerate(states)`. – Christian Dean Apr 07 '21 at 18:01
  • Thanks, just updated the question; now there are extra's `this is a test` in the output – AlSub Apr 07 '21 at 18:23
  • Well, you need to move the whole `if index == 0` business into the outermost loop, so it will only run once for the first item of the first list. Also, just a little tip, it's generally appreciated if questions aren't edited with new code as this can invalidate current asnwers. – Christian Dean Apr 07 '21 at 18:58

1 Answers1

0

It seems that you have improper indentation levels.

states=['Alabama', 'Georgia']
titles=['president', 'secretary']
codes=['A80', 'A81']

for state in states:
    for title in titles:             #4 spaces
         for code in codes:          #4 spaces
            while i==0:              #3 spaces
                print('just a test') #4 spaces
               if i > 0:             #3 spaces
                 continue            #2 spaces
               print(state+'-'+title+'-'+code) #3 spaces

proper indentation:

states=['Alabama', 'Georgia']
titles=['president', 'secretary']
codes=['A80', 'A81']

for state in states:
    for title in titles:
         for code in codes:
             while i==0:
                 print('just a test')
                 if i > 0:
                     continue
                 print(state+'-'+title+'-'+code) 

also, you never defined i, so you need to fix that.