Introduction
Using methods with lists gives you the power to manipulate the data stored in the lists quickly and effectively. Many of these methods are concerned with finding, adding, and removing pieces of data stored within the list they are being called on. Others are more concerned with the structure of the list itself.
In any case, they will make your experience using lists a lot less frustrating by saving you time and effort writing and rewriting the same code.
Finding the Length
Yes, this does start off with some more overlap with strings. The len()
method works on lists as well. So, in order to find the amount of elements in a list, just place it in the len()
method.
linux_distros = ['Debian', 'Ubuntu', 'Fedora', 'CentOS', 'OpenSUSE', 'Arch', 'Gentoo']
print(len(linux_distros))
Again, keep in mind that the result is the number of elements in the list. The last element is available at the index
of six. You can also use the len()
method to access elements in the list, if you have to.
linux_distros = ['Debian', 'Ubuntu', 'Fedora', 'CentOS', 'OpenSUSE', 'Arch', 'Gentoo']
print(linux_distros[len(linux_distros) - 1])
Adding the - 1
at the end is necessary, because there is no index
of seven, since the list starts counting at zero. Using this method is another way to access elements based on the length of the list. In some cases, it may be preferable to using the negative numbers.
Read more