Sign in to follow this  

[Python] for-in loops with multiple arrays

This topic is 2368 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):
[code]for bar in array0 + array1:[/code]

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
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.

[code]
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
[/code]

Share this post


Link to post
Share on other sites

This topic is 2368 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this