Skip to content

Instantly share code, notes, and snippets.

@gnud
Last active February 20, 2021 19:30
Show Gist options
  • Save gnud/cb05931444f228019cefe9c1afb39a1e to your computer and use it in GitHub Desktop.
Save gnud/cb05931444f228019cefe9c1afb39a1e to your computer and use it in GitHub Desktop.
from itertools import islice
class MyObject:
def __init__(self, text):
self.text = text
def text(self):
return self.text
default_empty = type('obj', (object,), {'text': ''})
# Let's access element with index 0 aka first element
n = 0
out0 = (
next(
islice(
[MyObject('mo1'), MyObject('mo2')],
n,
None
),
default_empty
)
).text
# Out:
# mo1
# Let's access element with index 100 (non existing)
n = 100
out100 = (
next(
islice(
[MyObject('mo1'), MyObject('mo2')],
n,
None
),
default_empty
)
).text
# Out:
# <blank text>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment