Python Forum
Is it possible to have an index (e.g., for a list) start at 1 instead of 0?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to have an index (e.g., for a list) start at 1 instead of 0?
#1
Is it possible to have an index (e.g., for a list) start at 1 instead of 0?
Reply
#2
You could put something in index 0 of the list that you never use.
You could -1 from from the number you want to index.
Reply
#3
You can also use ints as keys for dictionaries. You may not be able to loop like a list, but you can assign and retrieve by index that way. You can use this with collections.defaultdict for sparse lists, where the indexes might be high, but most of them are never used.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
If you need this index/integer for iteration then one can use enumerate:

>>> for i, char in enumerate("abc", start=1):
...     print(f"{i}. {char}")
...
1. a
2. b
3. c
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
(Aug-25-2019, 04:55 PM)perfringo Wrote: If you need this index/integer for iteration then one can use enumerate:

>>> for i, char in enumerate("abc", start=1):
...     print(f"{i}. {char}")
...
1. a
2. b
3. c

That's just what I needed. Thanks!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020