Python for Linguists
mystring = "I am a text, but in Python does not know that. To Python, I am just a sequence of characters."
myWordList = ["I", "am", "a", "list", "of", "words."]| element | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| index | 0 | 1 | 2 | 3 | 4 | 5 |
| 0 | … | … | … | … | len(s)-1 |
| element | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| index | -6 | -5 | -4 | -3 | -2 | -1 |
| -len(s) | … | … | … | … | -1 |
The left index is inclusive: It is the position of the first element in the slice.
The right index is exclusive: It is the index position of the first element outside of the slice.
Trying to access a single index outside of the actual range of of indices throws an IndexError: string/list index out of range.
Going outside the range when slicing is more forgiving.
Also, when your slice coincides with the beginning/end of a sequence, you can omit the corresponding index:
Define a string called test containing the word "hullaballoo".
Use slicing to extract the sequence "ball" from test.
Define a list called chomsky containing the words in the sentence "colorless green ideas sleep furiously".
Using slicing methods and other list operations, can you produce the list ["coloress", "green", "sleep", "furiously"]?
Challenge: What about ["furious", "sleep"]?


Bohmann: Python for Linguists, 2023