Python Lists

In Python, there are many ways to store collections of data in one item.

One of the easiest and most common ways is using a List!

Defining a List

Lists are defined with square brackets-

fruit_list = ["apple","banana","grapes"]
print(fruit_list)

List Functions

List Index

To know the index (position) of a string in the list, we use the index() function!

In this example, let’s say we want to know the index of “banana” in fruits_list. We can display the index by doing this-

fruit_list = ["apple","banana","grapes"]
position_banana = fruit_list.index("banana")

print(position_banana)
1

IMPORTANT: Python starts counting down from 0, not 1. So the position of “banana” in the list is actually 1, not 2. Don’t make that mistake!

List Length

We use the len() function to get the length of a list-

fruit_list = ["apple","banana","grapes"]
length_list = len(fruit_list)

print(length_list)
3

ANOTHER IMPORTANT THING: This is going to be confusing, but when it comes to finding the length, Python magically starts from 1 instead of 0 like usual. So the length of the fruit list is 3.

Alternate way: Using a For Loop

There’s another way to find the length of a list, and that’s by using a For loop. (Click here to know more about loops.)

fruit_list = ["apple","banana","grapes"]
length_list = 0

for item in fruit_list:
    length_list += 1

print(length_list)
3

In this code, for each fruit in fruit_list, we increase the length by 1. The total length is stored in a variable which we print out afterwards.

FUN FACT: No one really uses this. I just put this in here to lengthen my guide.

Appending

The append() function is used to add an element at the END of a list-

Inserting

The insert() function is also used to add an element, but with an index-

Removing

This is obvious. The remove() function is removes an element from the list.

Sorting

The sort() function rearranges the items of a list in ascending/descending order, or alphabetical order if the items are strings. Useful for perfectionists-

Conclusion

That’s all for this guide! I hope it this was helpful. I’ll add more information if I find any more useful ones.