3

I think that this question has been asked before, although I couldn't find an answer which fit with my query exactly.

I want to print certain elements from a list, depending on the length of an input. Example:

if anagramLength == 2:
    print(words[0,5])

I found a think called 'operator.itemgetter', although this selects individual elements, where as I want it to select all from position 0 TO position 5 (not position 0 AND position 5).

Thanks!

3
  • You mean words[0:5]? Commented Apr 18, 2020 at 17:23
  • ya thats want he meant i think Commented Apr 18, 2020 at 17:24
  • I did mean that. Thanks... ! Commented Apr 18, 2020 at 17:27

3 Answers 3

2

Just do the correct slicing:

words[0:5]

That is, replace the , by :

if anagramLength == 2:
    print(words[0:5])

The usage words[0,5], produces an error:

TypeError: string indices must be integers

To understand why the error is caused, do the following:

>>> 0,5
(0, 5)

See, it is a tuple. You can't slice a string with a tuple, but an integer :)

Sign up to request clarification or add additional context in comments.

6 Comments

So simple yet I didn't even try it. Thank you
I realised you said tick not upvote after I replied. Cheers :)
@WillLevine sure :) i think words[0,5] produces an error. did it? do you want to know why?
it did. how come?
@WillLevine i'll add that to the answer
|
1

You're looking for slicing.

The syntax is fairly simple:

words[start:stop]

Will print elements from start index to stop index, in your case:

print(words[0:5])

Comments

1

You can use slicing:

if anagramLength == 2:
    print(words[:5])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.