1

I'm trying to generate an alternating list of arrays with a loop, but I can't figure out the syntax. Currently I'm using the following code (as an example):

[ numpy.array([i,4,5]),numpy.array([31,4,i]) for i in range(5)) ]

It gives the following error:

"SyntaxError: invalid syntax"

I've tried , + and concatenate but it doesn't seem to work.

The desired output is the following list with alternating array entries:

[array([0, 4, 5]),
 array([31,  4,  0]),
 array([1, 4, 5]),
 array([31,  4,  1]),
 array([2, 4, 5]),
 array([31,  4,  2]),
 array([3, 4, 5]),
 array([31,  4,  3]),
 array([4, 4, 5]),
 array([31,  4,  4])]

Thanks everyone!

3
  • 2
    You've got to show us your expected output ... Commented Jul 7, 2015 at 2:39
  • I think I have what you wanted. Did I guess the right output? Commented Jul 7, 2015 at 2:46
  • Yeah that's it, thanks a lot! Sorry for the confusion, I'll adjust the question Commented Jul 7, 2015 at 2:48

2 Answers 2

4

What do you want to produce?

In [3]: [ (numpy.array([i,4,5]),numpy.array([31,4,i])) for i in range(5) ]
Out[3]:
[(array([0, 4, 5]), array([31,  4,  0])),
 (array([1, 4, 5]), array([31,  4,  1])),
 (array([2, 4, 5]), array([31,  4,  2])),
 (array([3, 4, 5]), array([31,  4,  3])),
 (array([4, 4, 5]), array([31,  4,  4]))]

Using a for loop, the same thing:

myList = []
for i in range(5):
   item = ( numpy.array([i,4,5]),numpy.array([31,4,i]) )
   myList.append(item)
print(myList)
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah exactly! They should alternate in the list. When I use + instead of , btw, it returns this: [array([31, 8, 5]), array([32, 8, 6]), array([33, 8, 7]), array([34, 8, 8]), array([35, 8, 9])]
Thanks! I'm trying to get the result without the brackets, so just as list with the items being the arrays, is that also possible?
@fransheg Can you please edit the original question and write down the exact expected output? I am not sure what you are looking for.
Sorry for the confusion! I've now added the desired output. The question is now solved in the answer of NightShadeQueen, thanks again.
2

There's probably no easy way to get around making a list of list of arrays, so using sum to add all the internal lists together to get one list of arrays. (see documentation here)

In [6]: sum([ [numpy.array([i,4,5]), numpy.array([31,4,i])] for i in range(5) ],[])
Out[6]: 
[array([0, 4, 5]),
 array([31,  4,  0]),
 array([1, 4, 5]),
 array([31,  4,  1]),
 array([2, 4, 5]),
 array([31,  4,  2]),
 array([3, 4, 5]),
 array([31,  4,  3]),
 array([4, 4, 5]),
 array([31,  4,  4])]

1 Comment

Cool. Can you edit your question to provide an example of the output you wanted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.