Friday, October 5, 2018

Lists in Python

We've already introduced Lists when we discussed about data structures in Python. In this post, we will cover Python lists, list functions, and list methods.

Let's begin with a brief review about Lists.

A list is also a built-in data structure available in Python. It can contain heterogeneous values such as integers, floats, strings, tuples, lists, and dictionaries. Python lists are mutable; yes, they can change.
The following are the characteristics of a Python list:
  • Values are ordered
  • Mutable
  • A list can hold any number of values
  • A list can add, remove, and alter the values
 The syntax to create a list is <Variable name > = []

Thus myList = [] creates an empty list.

In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas. Here’s a simple example of a list that contains a few kinds of motorbikes:

motorbikes = ['Honda','Yamaha','Suzuki','Royal Enfield', 'Harley Davidson']

Let us print this list , the program motorbikes.py demonstrates how we do it.




As you may have observer from the output in the above screenshot if you ask Python to print a list, Python returns its representation of the list, including the square brackets. But this isn’t the output we want to see, let’s learn some of the operations we can perform in a list.

1. Accessing List items (elements)

Lists are ordered collections, so you can access any element in a list by telling Python the position, or index, of the item desired. To access an element in a list, write the name of the list followed by the index of the item enclosed in square brackets. For example, let’s pull out the first bike in the list motorbikes:

The first element in the list can be accessed by motorbikes[0]. Thus if we say print(motorbikes[0]), the first bike in the list will be printed. See the program below-



 As you may have noticed in the above screen shot, when we ask for a single item from a list, Python returns just that element without square brackets or quotation marks. Also remember that Python considers the first item in a list to be at position 0, not position 1. The second item in a list has an index of 1. Using this simple counting system, you can get any element you want from a list by subtracting one from its position in the list. For instance, to access the fourth item in a list,
you request the item at index 3.

print(motorbikes[3])

In the program shown below we are printing all the elements in our motorbikes list.




Python has a special syntax for accessing the last element in a list. By asking for the item at index -1, Python always returns the last item in the list. So print(motorbikes[-1]) returns Harley Davidson. This syntax is quite useful, because you’ll often want to access the last items in a list without knowing exactly how long the list is. This convention extends to other negative index values as well. The index -2 returns the second item from the end of the list, the index -3 returns the third item from the end, and so forth.


Let's print all the elements in our motorbikes list using this convention. See the screen shot below-




So if it's asked which motorbike I purchased first my next program will answer -



 As you have seen we build a sentence using the value at motorbikes[0] and store it in the variable first_bike. The output is a simple sentence about the first bike in the list.

2. Modifying List items (elements)

To change an element, use the name of the list followed by the index of the element you want to change, and then provide the new value you want that item to have. For example if I want to have Suzuki Intruder instead of Honda , I'll do the following:

motorbikes[0] = 'Suzuki Intruder' 

See the program and output in the screenshot below-



First we have printed our original list , then we changed the first item Honda to Suzuki Intruder (motorbikes[0] = 'Suzuki Intruder' ) and finally printed our modified list.

3. Adding List items (elements)

What if I want to have my Honda bike back to my list of motorbikes? The simplest way to add a new element to a list is to append the item to the list. When you append an item to a list, the new element is added to the end of the list. Using the same list we had in the previous example, we’ll add the
new element 'Honda ' to the end of the list:

motorbikes.append('Honda')

See the screenshot below for the program and output:


 


The append() method adds 'Honda' to the end of the list without affecting any of the other elements in the list.

Can you think of other possible utility of append method ?

I for sure gonna use it to build lists dynamically. For example, you can start with an empty list favorite_languages and then add items to the list using a series of append() statements.

favorite_languages = [] 

favorite_languages.append('Python')

See the screenshot below:



First an empty list was created and printed. Then  Python was added as a favorite language followed by printing the modified list. Add few more languages and grow your list as shown below:




Building lists this way is very common, because we often won’t know the data the users want to store in a program until after the program is running. To put the users in control, start by defining an empty list that will hold the users’ values. Then append each new value provided to the list you just created.


4. Adding List items (elements)

 Consider a situation where Perl is my third favorite language and I want to change my list to reflect my situation. All I am looking for is to add a new item 'Perl' to my favorite_languages list. We can add a new element at any position in our list by using the insert() method. I do this by specifying the index of the new element and the value of the new item. So to make Perl my third favorite language, I'll write -

favorite_languages.insert(2,'Perl')

The screenshot below shows the implementation and the output

 

 

The insert() method opens a space at position 2 and stores the value 'Perl' at that location. This operation shifts every other value in the list one position to the right .



5. Removing List items (elements)

Now I no longer using 'C' language and thus I want to remove it from my list of favorite languages. This can be done using del statement provided we know the position of the item to be removed in the list.

So to remove 'C' language I'll use the del statement in the following way-

del favorite_languages[3]

The screenshot below shows the implementation and the output:



As you can see the 'C' language has been removed from the list. Remember you can no longer access the value that was removed from the list after the del statement is used, thus 'C' language item is permanently removed.

If we want to use the value of an item after we remove it from a list, we should use pop(). The pop() method removes the last item in a list, but it lets you work with that item after removing it. The term pop comes from thinking of a list as a stack of items and popping one item off the top of the stack. In
this analogy, the top of a stack corresponds to the end of a list.

Let’s pop a bike from the list of motorbikes:

popped_bike = motorbikes.pop()

The screenshot below shows the implementation and the output:




The output shows that the value 'Harley Davidson' was removed from the end of the list and is now stored in the variable popped_bike.


We can use pop() to remove an item in a list at any position by including the index of the item we want to remove in parentheses. Say to remove the first item we will use pop(0), second item pop(1) and so on.

Let's make a program which will show my first purchased bike and the last purchased bike.



We start by popping the first bike in the list first_bike = motorbikes.pop(0), the last bike in the list last_bike = motorbikes.pop(-1) and then printed the statements using the variables first_bike and last_bike. Remember that each time you use pop(), the item you work with is no longer stored in the list.


You must be wondering how to remove an item when the list is long and the position of the item is unknown. Say I have a long list of cars 'my_cars' and I want to remove 'Maruti' car from my list. This can be achieved by using the remove() .

my_cars.remove('Maruti')

 The screenshot below shows the implementation and the output:





The code my_cars.remove('Maruti') tells Python to figure out where 'Maruti' appears in the
list and remove that element.

The item removed can be used in the program just like it was reusable in case of pop(). So I write-

sold = 'Maruti'

my_cars.remove(sold)


The screenshot below shows the implementation and the output:



I stored the value 'Maruti' in a variable sold and then use this variable to tell Python which value to remove from the list. Hence 'Maruti has been removed from the list but is still stored in the variable sold, allowing us to print a statement My Maruti car has been sold as it was old!.

We'll continue to explore List in my next post, till then make some more programs and play with Python as Python is easy to learn!




Share:

0 comments:

Post a Comment