In my journey for learning Python (with NLP in mind) I have come across some basic 'list' methods, or what are known as 'array' methods in other languages (Javascript, PHP,...). I am writing them down here with examples so that I (and maybe you) can learn them much better. These are the method I am trying to give examples of:
- .append()
- .count()
- .choice()
- .sort()
Definition:
According to W3schools, Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
names = [ 'John' , 'Jack' , 'Ava' ]
#Lists can contain different data types
Address = [ 'Amsterdam' , 13 , True ]
To access the items in a list, we start from 0, so:
names = [ 'John' , 'Jack' , 'Ava' ]
# | | |
#names=[ 0 , 1 , 2 ]
#names[0] -> John
#names[1] -> Jack
#names[2] -> Ava
#Let's print the second name
print(names[1])
#This will print out John
To access the items of the list from the end we can use negative indexing. The last item has the index of -1:
names = [ 'John' , 'Jack' , 'Ava' ]
last_name = names[-1]
print(last_name)
# Will print out Ava
If you want to replace a list item (for example the second name) with another one i.e., update the names list:
names = [ 'John' , 'Jack' , 'Ava' ]
#changing Jack which has an index 1 with Sarah
names[1] = 'Sarah'
print(names)
# will print out ['John', 'Sarah', 'Ava']
To add a name to the end of our list we can use 'append()' method :
names = [ 'John' , 'Jack' , 'Ava' ]
#adding Ryan
names.append('Ryan')
print(names)
#will print out ['John' , 'Sarah' , 'Ava' , 'Ryan' ]
If you would like to know how many of an instance there are in the list:
names = [ 'John' , 'Jack' , 'Ava' , 'John' ]
#How many Johns are there?
x = names.count('John')
print(x)
#will print out 2 since there are two 'John' in the list
If you want to choose a random item from a list you can use random.choice() method. Note that you need to import Random module since you are using it:
import random
names= ["John", "Jack", "Ava"]
random_name = random.choice(names)
print(random_name)
#will print out one random item from the list
If you want to sort a list alphabetically or numerically (ascending or descending order):
names = [ 'John' , 'Jack' , 'Ava' , 'John' ]
names.sort()
#The list is now sorted alphabetically, the above method sorts the list
print(names)
#prints out ['Ava' , 'Jack' , 'John' , 'John' ]
#to reverse the order:
names.sort(reverse=True)
print(names)
#prints out [ 'John' , 'John' , 'Jack' , 'Ava' ]
You can use the same method for numbers
All right! these were the methods that I just learnt to work with! It is for beginners (like me) and I hope you have learnt something as well.