Tuesday, April 2, 2013

Adding to a List

     There is much more about lists, and since you know a little about them, I think you should know everything, so your questions about them will be answered sooner. First, let's learn about slicing shorthand. These are not all that necessary, but programmers are lazy, and you need to know the shortcuts you use, in case if you ever look at their code. First, there is a shortcut to get everything from the beginning of the list to the part you want it to go up to. Here's how:

print(family[:2])

['Jack', 'Tim']

     It doesn't seem to be much of a shortcut, but I guess it's some of one. Now, another pointless shortcut:

print(family[2:])

['Mom', 'Dad', 'Willy', 'Betty']

     So, we started at item #2 in the list, and went to the end. There's a third shortcut that seems to be the fastest out of all of these.

print(family[:])

['Jack', 'Tim', 'Mom', 'Dad', 'Willy', 'Betty']

     This time, there are no numbers. That tells Python to give you all items of the list. It only makes a copy of the list, so you can change it without affecting the original. Now, we will get into some more important matters of lists.
     You can change items in the list, like so:

family[2]='Nancy'

print(family)

['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty']

     We changed "Mom" to "Nancy." If you need to make any rearrangements, this will come in handy. You can also add things to a list using append(), extend(), or insert().
     First, we will start with append(). Here is how it works:

family.append('Louis')

print(family)

['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', 'Louis']

     Remember, append() adds only one item to the list. To prove my claim, try this:

family.append(['Jason', 'Jake'])

print(family)

['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake']]

     Don't take away the list in the list. We will take it away later. Now, let us move on to extend().
     Although append() adds one item, extend() adds as many items as you want. Try this:

family.extend(['Grandpa', 'Grandma', 'Alison'])

print(family)

['Jack', 'Tim', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']

     That is basically all we need to know about extend(), so let's move on to insert().
     Inserting an item into a list isn't adding an item to the end, but adding an item anywhere you want. Try typing this:

family.insert(2, 'Mike')

print(family)

['Jack', 'Tim', 'Mike', 'Nancy', 'Dad', 'Willy', 'Betty', ['Jason', 'Jake'], 'Grandpa', 'Grandma', 'Alison']

     So, "Mike" became the second item in the list, and "Nancy," the former second item, was pushed up by one in the list.
     Now you know more about lists! For now, you only know how to add to a list. There is more you can do with them. Make sure you have these functions in your head, because you will need to remember everything you can about Python and lists.

No comments:

Post a Comment