Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select certain elements from a list in python

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!


2 Answers

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 :)

like image 53
Joshua Avatar answered Dec 13 '25 09:12

Joshua


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])
like image 37
RMPR Avatar answered Dec 13 '25 08:12

RMPR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!