When running this

expr:=5;
for item in expr do
print(item);
od;

it prints 5 as expected. When when running

expr:=I; (* NOTICE this is complex I not the number 1 *)
for item in expr do
print(item);
od;

it prints the number 1 and not I

I am sure there is a good reason why this happens.

But what should one do to insure they get the complex I in the second example when iterating over a sum of numbers, which in this example happened to be just one number who is complex? I know I can add explicit check to avoid this edge case.

The problem is that I want to iterate of sum of iterms, One or more of them can be complex I. (it is a result of doing series expansion of function at infinity, and I want to iterate over each term in the series one by one).

expr:=9+I:
for item in expr do
print(item);
od;

Gives **9,1 **and not **9,I **

While

expr:=a+I:
for item in expr do
print(item);
od;

does now give exected output **I,a **and not **1,a**

What should one do to insure the for loop always get each term in the sum, even if it is complex?

I can't check the item inside the loop, because by then it is too late as the compelx I is lost already.

Is there a better way to iterate over sum of terms and look at each term as is and not lose the complex I in the way?

Maple 2022.1

**Update **

For now, I am doing this hack. Since the input is always a sum (with + or - terms), then I convert the input to string, split on delimitors and then parse the entries back to Maple and now it is a list so I can iterate over each term.

expr:=I+3:
String(expr):
StringTools:-SubstituteAll(%,"+","|+"):
StringTools:-SubstituteAll(%,"-","|-"):
StringTools:-Split(%,"|"):
map(Z->parse(Z),%):
for item in % do
print(item);
od;

And when expr is

expr:=1+5*I+sin(x)-sqrt(8)*I-a;

It is a hack, but I could not find a relaible way to iterate over each term in the sum of terms without losing the complex I if one term was complex. I need to test this more. It is meant to work only on expression which is sum of terms, which is where I will use it.

Compare the output of the above for** expr:=1-I; **

The for loop gives **1,-1** but the string hack gives **1,-I **which is what I wanted.

Ofcourse the above could fail if there is a "-" or "+" inside the term itself (for example **1+I+sin(1-x)** , but this do not happen for the cases I am using this for, which just looking at terms of series expansion around either zero or infinity. These will be just power series terms separated by "+" or possibly "-"

If there is better way do this, that will be great.