Python Indexing and Slicing Exercises - Solutions
Python Indexing and Slicing Exercises - Solutions¶
This is the companion solutions notebook to the article Python Indexing and Slicing: Complete Tutorial With Hand-On Exercises.
1. What does the code below produce, and what’s it doing? (You can run it to find out if you need to). Can you replace everything except the import with a print statement and a concise slice expression?
from string import ascii_uppercase
subset = ""
for idx, letter in enumerate(ascii_uppercase):
if idx %4 == 0:
subset = subset + letter
print(subset)
AEIMQUY
from string import ascii_uppercase
print(ascii_uppercase[::4])
AEIMQUY
2. Given the ascii_upercase we imported above, print the alphabet backward using a slice expression.
from string import ascii_uppercase
print(ascii_uppercase[::-1])
ZYXWVUTSRQPONMLKJIHGFEDCBA
3. There’s a needle in the haystack below. Extract it from the string. In addition to a slice expression, you’ll need the index
method on the str class and the len
function:
example = "Hay hay hay hey hey needle nah nah nah nah, hey hey, goodbye."
haystack = "Hay hay hay hey hey needle nah nah nah nah, hey hey, goodbye."
start = haystack.index('needle')
pos = haystack[start:start + len('strpos')]
print(pos)
needle
4. Using a slice expression, slice the list “count_to_ten” below to produce a list with: [9,6,3]
count_to_ten = [num for num in range(1,11)]
print(count_to_ten)
count_to_ten = [num for num in range(1,11)]
print(count_to_ten)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
count_to_ten = [num for num in range(1,11)]
print(count_to_ten[8:0:-3])
[9, 6, 3]
5. Given the following code, write a concise expression to index the word shrubbery from the tokens array:
tokens = "Is there anywhere in this town where we could buy a shrubbery".split(" ")
print(tokens)
['Is', 'there', 'anywhere', 'in', 'this', 'town', 'where', 'we', 'could', 'buy', 'a', 'shrubbery']
tokens = "Is there anywhere in this town where we could buy a shrubbery".split(" ")
print(tokens[-1])
shrubbery
6. The index value can be used to look up the location of an item in a list or other sequence. It returns the item’s index. Given the code below, what would you expect claim.index("Python")
to return?
claim = "The best Python examples are on CodeSolid.com!".split(" ")
print(claim)
['The', 'best', 'Python', 'examples', 'are', 'on', 'CodeSolid.com!']
Answer: claim.index("Python")
returns 2.
7. Given the following code, what does the first print statement do? What does the second print statement do?
greeting = "Hello"
print(greeting[4])
print(greeting[5])
Answer: The first print statement prints an “o”. The second print statement raises an IndexError.
8. How could you find the knights in the ‘introduction’ below?
introduction = "We are the knights who say ni!"
Answer: Use the expression introduction.index("knights")