-1

Consider

teams = [[], []]

I want to add a people to teams, but only if (1) they for the same company as the others in the team OR (b) if the team is currently empty. The straight-forward way would be:

for team in teams:
    if len(team) > 0: # could also use "if bool(team):"
        if team[0].company == new_person.company:
           team.append(new_person)
           break
        else:
            continue
    else:
        team.append(new_person)
        break
else:
    teams.append([])
    teams[-1].append(new_person)

To me that seems like many lines to make a simple decision. The complicating factor is the possibility of an empty list, which will give me an error if I try to look at a property of one of its elements.

How can I say if a_list is empty or a_list[0].property == something: in one line?

levraininjaneer
  • 1,157
  • 2
  • 18
  • 38

3 Answers3

4

You mean by this?:

...
if not a_list or a_list[0].property == something:
    ...
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can try this:

# hasatrr -> some safety check
if not a_list or (hasatrr(a_list[0], 'property') and a_list[0].property == something)):
    <perform your operation>
else:
    <perform your else operation>
J. Snow
  • 305
  • 2
  • 10
0

I found another way to do it by using what I found here, which I expanded on to get:

if next(iter(team, new_person)).company == new_person.company:

But U9-Forward's response is indeed the best way to do it, I think. Also, great to keep in mind what bruno desthuilliers said:

" the second operand of the or operator is only evaluated if the first operand is false (since if the first is true then the expression is true, which is the definition of a logical or"

levraininjaneer
  • 1,157
  • 2
  • 18
  • 38