Embarrassingly, i don't understand how list indexing works
Curious how Python list indexing works
Hello, I'm a bit new to python.
I'm currently learning about slicing; I was very confused as to why we use the 0 index to represent index 1, but 4, for example to represent the fourth letter? makes no sense please help
I'm learning data structure and algorithms and i came across a question in the list section. i thought after i had understood python, i had understood list but a question was asked and i find myself finding it hard to understand how the list indexing works.
here's the sample code:
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
it looks simple to understand but, i just can't understand it.
An index, in your example, refers to a position within an ordered list. Python strings can be thought of as lists of characters; each character is given an index from zero (at the beginning) to the length minus one (at the end).
For the string "Python", the indexes break down like this:
P y t h o n
0 1 2 3 4 5
In addition, Python supports negative indexes, in which case it counts from the end. So the last character can be indexed with -1, the second to last with -2, etc.:
P y t h o n
-6 -5 -4 -3 -2 -1
Most of the time, you can freely mix positive and negative indexes. So for example, if you want to use find only from the second to second-to-last characters, you can do:
"Python".find("y", beg=1, end=-2)
"index" is meant as "position".
Let's use find() as an example: find() will look for a string in another string. It will start its search at the beginning index called beg and will end its search at the end index called end. So it will only search between beg and end. Usually (by default) beg is 0 (which means it is the first character in the string) and end is the length of the string minus one (which means it is the very last character in the string). So an index is just a position (not only in a string, e.g. also in an array).
Sorry if this question has an easy answer - I couldn't find one, but I might be using the wrong search terms.
From what I understand about arrays, the general process to index into an array is that there is a pointer that points to the base address of the array and consequently, the desired element can be retrieved by multiplying the element index by the size of the single element.
However, lists are data structures built into Python that also offer the same ability to index but also allow for different element types. So how does indexing work when the size of elements is not constant?
This also led me to believe that Python list are linked list, but searching that up revealed a couple of articles showing how to implement linked list into Python as they are not within the standard library:
https://www.geeksforgeeks.org/python-library-for-linked-list/
https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm