Monday, November 20, 2017

Lists and Tuples in Python

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.

Tuples
Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:
months = ('January','February','March','April','May','June','July','August','September','October','November','December')

Python then organises those values in a handy, numbered index - starting from zero, in the order that you entered them in. It would be organised like this:

Index
Value
0
January
1
February
2
March
3
April
4
May
5
June
6
July
7
August
8
September
9
October
10
November
11
December

Lists
Lists are very similar to tuples. Lists are modifiable (or 'mutable'), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.
Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:
print(cats[2])
You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats.
Where lists come into their own is how they can be modified. To add a value to a list, you use the 'append()' function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:
cats.append('Catherine')


No comments:

Post a Comment