#๐Ÿ”’ Python len function confusion

40 messages ยท Page 1 of 1 (latest)

noble osprey
#

can someone explain to me the necessity for -1 in the len function?

onyx moonBOT
#

@noble osprey

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

trail folio
noble osprey
#

sry i mean randint

#

the book says something about how python thinks index starts at 0

#

but I don't understand how the -1 still

trail folio
#

!e

import random

help(random.randint)
onyx moonBOT
# trail folio !e ```py import random help(random.randint) ```

:white_check_mark: Your 3.13 eval job has completed with return code 0.

001 | Help on method randint in module random:
002 | 
003 | randint(a, b) method of random.Random instance
004 |     Return random integer in range [a, b], including both end points.
trail folio
#

if u look at the help for it, u will see how it includes both end points

#

unlike the builtin range

noble osprey
#

oh right but i need it to return only one valu

#

e

#

is that it?

trail folio
noble osprey
#

but wouldnt that only be an issue if you had 2 items in your list

trail folio
#

if u had 2 items then len will return 2

#

since it has 2 items then the possible indexes are 0 (the first item) and 1 (the 2nd item)

#

there is no index 2

iron flicker
#

!docs random.randint

onyx moonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
trail folio
noble osprey
#

I see what you mean now

#

thanks

trail folio
iron flicker
iron flicker
trail folio
# onyx moon

also might be just me but the help() one for this sounds more friendly to beginners

noble osprey
#

woops

#

sry didnt mean

#

to tag for that

trail folio
#

its with a !

noble osprey
#

ohhh right

trail folio
#

also discord native close works too

#

or u can wait 1h of inactivity

noble osprey
#

!close

onyx moonBOT
#
Python help channel closed with !close

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.