If I haven't mentioned this already, it's impossible to change numbers and strings. Not unless a variable (or name) is assigned to them. With lists, you can change whatever's in it. Appending, deleting, sorting, reversing, all that stuff. These things are called mutable and immutable.
Mutable means something can be changed. It is "changeable." Immutable means it can't be changed.
Is there such a thing as an immutable list? Yes there is. It's called a tuple. Type this in Python IDLE:
tuple1=("Apples", "Bananas", "Watermelon")
Instead of square brackets ([]), we used parenthesis (()). Once you make this list, you can't change it. Well, you could change it if you write it in a program, but that's not the point. You can't append, pop, delete, extend, insert, sort, reverse, or any of those things you can do with a normal list. This is an immutable list.
It's useful to visualize how data is stored in a program.
A variable has a single value. person --> 'Bob'
A list is like a bunch of values assigned to one variable. family --> 'Jack', 'Tim', 'Mom', 'Dad', 'Willy', 'Betty'
Sometimes you need to make a table, a chart with rows and columns.
traits --> Eye color Widow's peak Freckles Left handed
Jack | Blue | No | Yes | No
Tim | Green | No | No | Yes
Willy | Blue | Yes | No | No
Wait, what? A table? In order to do that, we make a series of lists.
We could make a list of traits for each person, like so:
>>> jackTraits=['Blue', 'No', 'Yes', 'No']
>>> timTraits=['Green', 'No', 'No', 'Yes']
>>> willyTraits=['Blue', 'Yes', 'No', 'No']
Or we could organize the table in columns, like this:
>>> eyeColor=['Blue', 'Green', 'Blue']
>>> widowsPeak=['No', 'No', 'Yes']
>>> freckles=['Yes', 'No', 'No']
>>> leftHanded=['No', 'Yes', 'No']
We might want to collect this data together in a little something called a data structure.
I'll be using the rows, just so you know. It doesn't really make a difference, except the layout will be different in the end. First, let's make another list.
traits=[jackTraits, timTraits, willyTraits]
print(traits)
[['Blue', 'No', 'Yes', 'No'], ['Green', 'No', 'No', 'Yes'], ['Blue', 'Yes', 'No', 'No']]
That is a list of lists. Each item in the list is a list itself. Now, to display it in a table...
for allTraits in traits:
print(allTraits)
['Blue', 'No', 'Yes', 'No']
['Green', 'No', 'No', 'Yes']
['Blue', 'Yes', 'No', 'No']
There we go. Doesn't quite look like a table, but it helps to visualize it like one.
This article is getting a bit too long! Keep those lists ready, because we'll continue this in the next one!
No comments:
Post a Comment