Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

269
Views
Syntax for returning the entire list when using the minus sign?

Python lists have nifty indexing/slicing capabilities. Here are several examples:

x = "123456"

x[:-3]
'123'

x[:-1]
'12345'  # -1 slices off last element

x[:-0]  # -0 slices off .. everything .. this is what i'd like to fix
''

I would like to slice off a variable number of elements d:

x[:-d]

But if d were 0 we get a much different result than desired. A workaround is:

d = 0
x[:-d if d else len(x)]
'123456'

That is possible - but is there any [shorter] alternative?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

The issue you're hitting is that -0 is the same as 0, and x[0:0] is an empty slice.

I'd suggest:

x[:len(x)-d]
over 4 years ago · Santiago Trujillo Report

0

You could use None, which is the default for missing start/stop/step values:

x[:-d or None]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!