Post

Python Programming
Python Programming@PythonPr·
Python Question / Quiz; What is the output of the following Python code, and why? Comment your answers below!
Python Programming tweet media
English
20
6
113
10.5K
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr Answer: A Solution: This is an application of slicing and negative indices. You must be familiar with the usual indexing that starts from 0 (starting from the left). Negative indexing is a cool feature of python. It allows you to count backwards (from the right). Eg +
English
1
0
4
645
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr nums = [1, 2, 3, 4] If you want to access the last item, you'd have to do something like num[len(nums)-1] clunky and un-pythonic. Instead, you can use -1 to access the last item, like so: num[-1] # access last (rightmost) item What about the 2nd-last item? Got you covered +
English
1
0
0
51
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr You can count backwards from the rightmost item. The 2nd-last is at index -2, the 3rd-last at -3, and so on. See image: Applying to this question +
Coding Computing Coach tweet media
English
1
0
1
58
Coding Computing Coach
Coding Computing Coach@CodingComputing·
@PythonPr We have a slicing, from (-3) to (-1) ie, from 3rd-last to the last. nums = [1, 2, 3, 4] so, 3rd-last is 2. The last is 4. The slice starts from the start index and excludes the stop index. So, the output is: [2, 3] I hope this helped!
English
0
0
1
44
Paylaş