Mastering the use of lists and loops is one of the 5 fundamental skills of building algorithms:
A list is, normally, any collection of values. The rules of how to add or remove elements from that list can change from one programming language to another. But – generally – they are the only ways for developers to create elements. Lists are not the only way we have to list store multiple values at once but it is the most used tool for that purpose. For example: list of students, list of artists, list of transactions…anything!
This primitive data-type does a lot more stuff than the others.
Every list has the same basic concepts:
The items: are the actual values inside in each position of the list.
The length: is the size of the list (how many items the list has).
Index: is the position of the element.
☝List positions start a zero (0); the first element is the element in the position zero (0)
These are different examples of list declarations:
To access a specific element in a list, you need an
index. We call
index the integer value that represents the position of the element you want to access/get/retrieve.
The index always must start at zero (0). That means that an List of 2 items can have index=0 or index=1. Trying to get the 2nd position will return "undefined" because it will mean that we are trying to access the third element (which does not exist). For example, to get any items in the list you can do the following:
If you want you can reset or update any item inside of a list using its index like this:
appendin Python Lists
The first way is to add the element to the end of the list, you should use this method every time you can because it's a lot faster than
insertin Python Lists
Using insert is easier for the developer because it will let you pick the positions in which you want to inster the element, but it is a slower method (worse performance):
Python has many ways to delete an element from a list
It will remove the last element only!
It will let you remove the first occurence of an element by its name.
It will allow you to delete many items at once, you have to specify starting possition and ending possition.
Normally, when you manipulate lists, you have to loop all the items. For example: order them manually, flip them, filter them, etc.
There are many ways you can loop an entire list but the most used one is the
Sometimes it is useful to loop the array using each element's position (index). We can do that by using the
By default the
range will start from index zero and continue until a specified number is reached, not including that index number:
It is also possible to specify the starting index in the range, as well as the increment, by adding a starting point (the first parameter), and an increment value (the last parameter) in the range method:
All rights reserved, 4Geeks LLC 2021. Read more about 4Geeks and what we are going here.