Search code examples
pythonlistloopslogicenumerate

Looping over an enumerating list - how to skip a number?


In the following simple loop example, I would like to end up with 12 axes names sequentially by skipping one of the entries in a list of 13 data columns.

question_list=['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6a', 'Q6b', 'Q7', 'Q8','Q9', 'Q10', 'Q11', 'Q12']

for c, z in enumerate(question_list):
    if '6b' not in z:
        axis_names='ax_corr_'+str(c+1)
    print(axis_names)

Instead, I get the entry "ax_corr_6" two times in the resulting list axis_names. I do not understand why the entry for 6b was not simply skipped and the enumeration advanced to 7. It leads me to believe I don't quite understand how to encode this simple logic in Python. Can anyone clarify why this happens and how to achieve a list that skips 'Q6a?


Solution

  • Well, you're trying to print the index except when 6b will be miss matched. Try a debug and print Z it really works or not. Find the output of my code and will be seen 6b is skipping.

    for c, z in enumerate(question_list):
        if '6b' not in z:
            print('For '+z + ' ax_corr_'+str(c+1))
    

    For better understanding follow up the output where 6b is skipped.

    For Q1 ax_corr_1
    For Q2 ax_corr_2
    For Q3 ax_corr_3
    For Q4 ax_corr_4
    For Q5 ax_corr_5
    For Q6a ax_corr_6
    For Q7 ax_corr_8
    For Q8 ax_corr_9
    For Q9 ax_corr_10
    For Q10 ax_corr_11
    For Q11 ax_corr_12
    For Q12 ax_corr_13