python for loop list plus one item

I'm handling mouse clicks on objects based on the location of the object on the screen. I record the xy coord of the mouse click and see if it matches any of the objects that are allowed to be clicked on. The objects are in different lists or just single objects, but I want them in one big list so I can just loop through the whole thing once, if the click is on one of the objects, do the work, break. You can only click on one object.

First method: how i'm doing it now:

list = [obj1, obj2, obj3]
singleobj

copylist = list
copylist.append(singleobj)

for item in copylist:
    if item.pos == mouseclick.pos:
        doWork(item)
        break

Second method: I'd rather do something like below, but obviously the list+singleobj is not valid:

for item in list+singleobj:
    if item.pos == mouseclick.pos:
        doWork(item)
        break

Third method: Or if I absolutely had to, I could do this horrible terrible code:

list = [obj1, obj2, obj3]

foundobj = None

for item in list:
    if item.pos == mouseclick.pos:
        foundobj = item
        break

if foundobj is None:
    if singleobj.pos == mouseclick.pos:
        foundobj = singleobj

#possibly repeated several times here....


if foundobj is not None:
    doWork(foundobj)

The first method seems slow because I have to copy all of the (possibly many) lists and single objects into one list.

The second method seems ideal because it's compact and easy to maintain. Although, as it stands now it's simply pseudo code.

The third method is bulky and clunky.

Which method should I use? If the second, can you give the actual code?

Answers


For 2nd method you need itertools.chain

for item in itertools.chain(list, [singleobj]):
    ...

Need Your Help

How to populate dropdownlist with hours in c#

c# asp.net drop-down-menu

I have to 2 dropdownlists and I want to populate them with their values as hours from 1 to 24. Then I want to calculate the difference between the two selected values. If i choose in the first drop...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.