In our last article we learned to add rows and columns to a two-dimensional list. We are going to continue this discussion, briefly, by showing you how to use some functions to accomplish the same goals.
You may remember from our conversation about normal lists that there are several functions available to add and remove items. Namely they are pop, push, shift, and unshift. They work pretty similar with two-dimensional lists, but with some minor changes. Don't worry; I won't eat up a lot of time showing how to use these functions here, as that would mostly be repetitive. Still, the changes are important to note.
As you may recall, unshift() adds an element to the leftmost position, or beginning of a list. It does the same thing in two-dimensional lists. The only difference is the code:
@Bookshelf = (
[" # ", " Author ", " Title ", " Genre ", " Rating ", " Location "],
[' 1 ', ' Stephen King ', ' It ', ' Horror ', ' 5 ', ' Top '],
[' 2 ', ' Clive Barker ', ' Imajica ', ' Horror ', ' 5 ', ' Top '],
[' 3 ', ' Neil Gaiman ', ' American Gods ', ' Dark Fantasy ', ' 5 ',
' Top '],
[' 4 ', ' Dean Koontz ', ' Tick-Tock ', ' Horror ', ' 1 ', '
[' 5 ', ' Charles Bukowski ', ' Letters from a Dirty Old Man ', '
Literature ', ' 5 ', ' Top '],
[' 6 ', ' Chuck Pahluniak ', ' Fight Club ', ' Dark Fantasy ', ' 5 ',
' Middle ']
unshift(@Bookshelf, [' 1 ', ' T.H. White ', ' The Once and Future King
','Fantasy ', ' 5 ', ' Middle ']);
When you run this code, it prints out the new record in row 0:
1 T.H. White The Once and Future King Fantasy 5 Middle
You will note that the record that previously held the 0 row position is now moved to row 1, and row 1 is now row 2, and so forth. This of course messes up our use of row 0 as a header with all of the column names, but we can fix that later.
blog comments powered by Disqus