Python Forum
Why do I have to repeat items in list slices in order to make this work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do I have to repeat items in list slices in order to make this work?
#2
Slicing starts at the start number and ends before the end number. I think this is because indexing starts at 0.
things = "abcdefg"
print(things[:3])  # Print the first 3 letters.
If the slice contained the ending value you would write this:
things = "abcdefg"
print(things[:2])  # Print the first 3 letters.
Hmmm. I want three values, but I need to ask for 2?

range() use the same protocol.
for i in range(3):  # I want to iterate 3 times
    print(i)
Output:
0 1 2
Similar to slicing, range would look odd if the range included the end number.
for i in range(2):  # I want to iterate 3 times.  Why do I need to enter 2?
    print(i)
When you start with zero, the number in range(number) equals the number of iterations. You can set the start number to any value, but by a huge margin most range(start, end, increment) skip setting the start and increment.
Pythonica likes this post
Reply


Messages In This Thread
RE: Why do I have to repeat items in list slices in order to make this work? - by deanhystad - May-19-2023, 04:21 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Make a list learningpythonherenow 1 872 Oct-11-2024, 11:49 AM
Last Post: Pedroski55
  Trying to Make Steganography Program Work For All Payload Types Stegosaurus 0 1,201 Sep-26-2024, 12:43 PM
Last Post: Stegosaurus
  How to make my Telegram bot stop working at 16:15 and not work on Fridays? hus73 2 1,406 Aug-10-2024, 12:06 PM
Last Post: hus73
  Extending list doesn't work as expected mmhmjanssen 2 1,432 May-09-2024, 05:39 PM
Last Post: Pedroski55
  Copying the order of another list with identical values gohanhango 7 2,676 Nov-29-2023, 09:17 PM
Last Post: Pedroski55
  hi need help to make this code work correctly atulkul1985 5 1,980 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  tuple indices must be integers or slices, not str cybertooth 16 19,484 Nov-02-2023, 01:20 PM
Last Post: brewer32
  newbie question - can't make code work tronic72 2 1,560 Oct-22-2023, 09:08 PM
Last Post: tronic72
  No matter what I do I get back "List indices must be integers or slices, not list" Radical 4 2,664 Sep-24-2023, 05:03 AM
Last Post: deanhystad
  Beginner: Code not work when longer list raiviscoding 2 1,752 May-19-2023, 11:19 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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