Hello fellow coders, I’m new to coding and would like to know how indexes are useful, i’m certain they have roles to play in higher complicated programs but if someone could just simply break down why indexes are used i’d really appreciate that. Thanks
Indexes keep track of lists (aka arrays). Lists are everywhere. Think about a list of computer files, YouTube videos, or lasagna recipes.
Indexes allow you to get the 1st, 2nd, 3rd etc. item in a list. If I clicked on the 3rd link to a recipe in a list, the computer knows which recipe to get based on that index.
Indexes also allow you to loop over a list. If I want to add text to a list of computer files, I start adding the text to the first file and increment that index to find the next file.
Hope this helps
An index is a sequence of integers starting at zero and increasing by 1’s. An index is said to be ordered in that it never changes. Always the sequence is 0…n, even after sorting or jumbling a list, the indexes do not move, only the items get moved around in the list.
Lists are the most common indexed objects, but they are not alone. Strings are indexed by character position, starting with index 0 as the first letter in the string.
You will learn later about tuple and set as being indexed, as well. No matter what order the items are in, the index is always ordered.
The index is not a stored value, but a computed one. Consider each item in a list as having a unique memory location. When the list is stored, the memory slots are allocated and populated from start to end in the order in which they occur in the list. When the computer is looking for an item by index, it goes to memory and retrieves the (n+1)th item.
Strings are not stored the same way (they get a contiguous block of memory), but their indexes can still be computed by counting the bytes in the string.
Whenever you see variable[i], variable is the name of the object, and [i] is the index being referenced.
fruits = ['apple', 'orange', 'banana', 'pear', 'lemon', 'lime', 'grapefruit']
Each of the items in the list can be retrieved by their index. The first index is 0, the last index is one less than the length of the list.
print (fruits) # apple length = len(fruits) # 7 print (fruits[length - 1]) # grapefruit
Note above that we use the built in function,
len() to find the length of an iterable. Lists, strings, tuples, sets, and dictionaries are all iterable objects. You will learn in more detail about dictionaries, sets and tuples as the course progresses. For now just focus on strings and lists while you master the concept of working with indexes.
In Python, and some other languages, indexes can also be negative. This tells the interpreter to read from right to left instead of the normal left to right.
print (fruits[-1]) # grapefruit print (fruits[-7]) # apple