- Nick Congleton
IntroductionUsing 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 LengthYes, 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
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
indexof 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
- 1at the end is necessary, because there is no
indexof 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.