Python Indexing and Slicing Exercises

Python Indexing and Slicing Exercises

This is the companion exercises 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
# Add your solution here:

2. Given the ascii_upercase we imported above, print the alphabet backward using a slice expression.

from string import ascii_uppercase
# Add your solution here:

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:

haystack = "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."
# Add your solution here:

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)]
# Add your solution here:

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(" ")
# Add your solution here

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!']

Write your answer here:

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

Write your answer here:

8. How could you find the knights in the ‘introduction’ below?

introduction = "We are the knights who say ni!"

Write your answer here: