Jump to content
  • Advertisement
Sign in to follow this  
wquist

[Python] for-in loops with multiple arrays

This topic is 2551 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

I was looking at some python code, and coming from an Obj-C background, I was having some trouble understanding for-in loops that combine arrays with a '+'. Something that looks like this, where I have a variable (bar) and two arrays (array0 and array1):
for bar in array0 + array1:

Does this just loop through both arrays separately, or does it combine them, and exclude identical items? Like, if I had an object 'foo' in both arrays, would it only output it once.

Sorry I don't have a python compiler to run some tests.
Thanks :)

Share this post


Link to post
Share on other sites
Advertisement
If those really are arrays ('lists' is actually the name used in Python), then they will be concatenated before the iteration occurs. There's no removal of duplicate items. Python has a built-in 'set' class that would provide that behaviour, though.


Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> array0 = [1,2]
>>> array1 = [2,3]
>>> for bar in array0 + array1:
... print bar
...
1
2
2
3
>>> for bar in set(array0 + array1):
... print bar
...
1
2
3

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!