Indexing & Slicing

1. Describe indexing.
Indexing refers to accessing individual elements within a data structure using their position or index. In Python, indexing is zero-based, meaning the first element is at index 0, the second at index 1, and so on.
2. Explain negative indexing.

Negative indices count from the end of the sequence, with -1 representing the last element, -2 representing the second-to-last, and so forth.

my_list = [1, 2, 3, 4, 5]
my_list[-1]  # Output: [5]
3. Describe slicing.
Slicing involves extracting a portion or a subset of elements from a sequence (e.g., a list, string, tuple) based on a specified range of indices.
4. Explain the slicing syntax [start:stop:step] and their default values if they’re not specified.
  • start: Marks the index of the character to start. Default to index 0.
  • stop: Marks the index of the character to stop, not including the position of the character. Defaults to index -1.
  • step: The sequence of counting. Defaults step size to 1.
5. Given a string s = "aieouabc", return s[2].
e
6. Given a string s = "aieouabc", return s[2:].
eouabc
7. Given a string s = "aieouabc", return s[2::].
eouabc
8. Given a string s = "aieouabc", return s[1:1].
‘’
9. Given a string s = "aieouabc", return s[].
SyntaxError
10. Given a string s = "aieouabc", return s[:3].
aie
11. Given a string s = "aieouabc", return s[-5].
o
12. Given a string s = "aieouabc", return s[-4:].
uabc
13. Given a string s = "aieouabc", return s[-5:2].
‘’
14. Given a string s = "aieouabc", return s[-5:-2].
oua
15. Given a string s = "aieouabc", return s[-5:-7:1].
‘’
16. Given a string s = "aieouabc", return s[-5:-7:-1].
oe
Last updated on 19 Nov 2023