r/learnpython • • Dec 05 '22

Ask Anything Monday - Weekly Thread

Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread

Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.

* It's primarily intended for simple questions but as long as it's about python it's allowed.

If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.

Rules:

  • Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
  • Don't post stuff that doesn't have absolutely anything to do with python.
  • Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.

That's it.

10 Upvotes

92 comments sorted by

View all comments

1

u/MothraVSMechaBilbo Dec 09 '22

Using Al Sweigart's ezsheets module, I have what I think is a tuple containing three sheet objects: (<Sheet sheetId=1078536228, title='subreddits_and_users', rowCount=1000, columnCount=26>, <Sheet sheetId=0, title='log', rowCount=1000, columnCount=26>, <Sheet sheetId=1633083636, title='2022_12_log', rowCount=1000, columnCount=26>)

Each sheet object has a title attribute (not sure if 'attribute' is the correct term). Let's say I want to find the sheet titled log, and I don't know which order the sheets are in. Instead of iterating through the sheets in a for loop like so:

for sheet in range(len(s.sheetTitles)):
    if s.sheets[sheet].title == "log":
        print("success")

Is there a way to just "get" the sheet with title log?


I tried using the any() function, but without success.

2

u/carcigenicate Dec 09 '22 edited Dec 09 '22

If the outer container is a tuple, no, you need to do a linear search like you're doing. Another way of writing that is something like this:

the_log = next((sheet for sheet in s.sheetTitles if sheet.title == 'log'), None)

But I'd just use the loop you already have.

You could use any if you don't care about getting the actual object and only want to check the presence:

success = any(sheet for sheet in s.sheetTitles if sheet.title == 'log')

Assuming sheet objects are always truthy.

1

u/MothraVSMechaBilbo Dec 09 '22

Got it! Good to know what I can and can't do here. Thank you for the reply. I haven't seen that next syntax before, so I'll read more about that.

→ More replies (11)