Python 101 – Lists, Tuples
Lists
A list in python is created by using square brackets, and seperating values using commas.
list = ['first', 'second', 'third', 'forth']
All of the values within the list can be shown by calling the entire list
print(list)
['first', 'second', 'third', 'forth']
You are able to access specific values within the list by specifying the index value
print(list[0])
first
To update a value within the list you need to specify the index value, similar when you read the value
list[0] = 'last'
print(list[0])
last
Finally, to delete a value within a list, you can do the following
del list[0]
print(list)
['second', 'third', 'forth']
Tuples
A tuple is similar to a list, where it is a collection of objects, however a tuple cannot be changed unlike lists. A tuple is created either with or without parenthesis.
tup1 = ('first', 'second', 'third')
tup2 = 'fourth',
Notice how ‘tup2’ has only one value, but it must contain a comma after the value.
Tuples are accessed the same way as lists
print(tup1[0])
first
As previously mentioned, tuples cannot be updated or modified, however you can join two tuples together.
tup3 = tup1 + tup2
print(tup3)
('first', 'second', 'third', 'fourth')
You cannot delete values within a tuple, but you can create a new tuple and exclude the values you no longer want. To remove an entire tuple, you can use del, similar to lists:
del tup3
Leave a Reply