Python Data Types

Python Data Type – Lists

In the section above, you learned about string data types – their use, indexing, string concatenation, and string multiplication.

Let’s now introduce a new data type called list.

Python lists are a compound data type.  Whereas a string is a contiguous sequence of characters, lists are ordered sequences of items. Each item in the list is separated by commas.  The complete list of items is enclosed in square brackets [   ].

Python interpreter assumes the data type to be a list, if the complete list is enclosed in square brackets like [   ] and the individual items are separated by commas.

Lists can be used to store numbers, words, or even strings.  Here are some examples of Python lists.

>>> Number_list = [1, 5, 6, 8]
>>> Words_list = [ ‘Robert’, ‘Michael’, ‘Tricia’]
>>> planet_list = [‘mercury’, venus’, ‘earth’, ‘mars’, ‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’]
>>> [] # This is empty list.

Why Use Lists

The list data type is more powerful and much more versatile than the string data type.  Whereas strings cannot be manipulated (changed, added to, or deleted from) since they are immutable, lists can be manipulated, that is, any item in the list can be changed or deleted, or new items can be added to the list. Thus, lists are mutable. This property makes the lists much more useful than strings, as we will see in the next few example programs.

How To Use Lists

To show how lists can be used, we will use the facts of our solar system as example.

Let us make a list using the names of the planets of the solar system. Our solar system has eight planets. The four planets closer to the sun are Mercury, Venus, Earth, and Mars.  These are called inner planets. The remaining four planets (Jupiter, Saturn, Uranus, and Neptune) are farther from the sun and are called outer planets.  Note the use of square brackets and commas separating the items in the list.

>>> inner_planets = [‘mercury’, ‘venus’, ‘earth’, ‘mars’]
>>> outer_planets = [‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’]

List Concatenation (Joining or Addition)

Similar to string concatenation, lists can be joined (addition) using the concatenation operator (+).  To make a list of all eight planets, we can use the concatenation operator (+) to join the ‘inner_planet’ list and the ‘outer_planet’ list as in the program below.

PROGRAM EXAMPLE: LIST CONCATENATION (JOINING or ADDITION)
>>> inner_planets = ['mercury','venus','earth','mars']
>>> outer_planets = ['jupiter','saturn','uranus','neptune']
>>> # Let us print inner_planet list and outer_planet list.
>>> print(inner_planets)
['mercury', 'venus', 'earth', 'mars']
>>> print(outer_planets)
['jupiter', 'saturn', 'uranus', 'neptune']
>>> 
>>> # Let us now concatenate inner_planets list and outer_planets list.
>>> inner_planets + outer_planets
['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']
>>> 
>>> # Use print statement to concatenate inner_planets and outer_planets
>>> print(inner_planets + outer_planets)
['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']
>>> 
>>> 
>>> # Another concatenation example using a list variable and an explicit list.
>>> inner_planets +['jupiter','saturn','uranus','neptune']
['mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', 'uranus', 'neptune']
>>>

In the above program, lists are made out of characters to show the concatenation of lists.  We will now write a program that has lists made out of digits.

PROGRAM EXAMPLE: CONCATENATION OF LISTS COBSISTING OF DIGITS
>>> numbers_1 = [1, 2, 3, 4, 5]
>>> numbers_2 = [6, 7, 8, 9, 10]
>>> # We will concatenate list ‘numbers_1’ and list ‘numbers_2’.
>>> numbers_1 + numbers_2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> 
>>> # Let us use print() function to concatenate and print the combined list
>>> print(numbers_1 + numbers_2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> # You can also concatenate list variable with an explicit list.
>>> print(numbers_1 +[11 , 12])
[1, 2, 3, 4, 5, 11, 12]
>>>

List Multiplication (Repetition)

You might wonder if we can repeat (multiply) lists just as we did the multiplication of strings. Yes, we can. Multiply operator (*) can be used for the repetition of lists similar to strings as in the example below.

PROGRAM EXAMPLE: LIST MULTIPLICATION (REPETITION)
>>> # Multiply list made of numbers
>>> number_list = [2, 3, 4, 5]
>>> 2 * number_list # multiply list items by 2
[2, 3, 4, 5, 2, 3, 4, 5]
>>> 
>>> # Multiply explicit list
>>> 2 * [2, 3, 4, 5]
[2, 3, 4, 5, 2, 3, 4, 5]
>>> 
>>> # Multiply list made of characters
>>> planet_list = ['mercury', 'venus', 'earth']
>>> 3*planet_list
['mercury', 'venus', 'earth', 'mercury', 'venus', 'earth', 'mercury', 'venus', 'earth']
>>>

Indexing in Lists

In the previous section, we learned about indexing in strings. Now let us see how we can use indexing for the list. Indexing of list items is similar to indexing in strings. The first item in the ordered list has an index of 0, the second item in the list has an index of 1, the third item in the list has an index of 2, and so on. Slicing, as used in strings, also works for lists.

Let us again use the inner_planets list defined earlier to explain indexing in lists.

>>> inner_planets = [‘mercury’, ‘venus’, ‘earth’, ‘mars’]

PROGRAM EXAMPLE: LIST INDEXING
>>> # indexing in lists
>>> inner_planets = ['mercury','venus','earth','mars']
>>> # Now print planet venus by using index = 1
>>> print(inner_planets[1])
venus
>>> 
>>> # Now print planet mars by using index = 3
>>> print(inner_planets[3])
mars
>>> # The list has four items (index from 0 to 3).  
>>> Let us try what happens if we use an index > 3
>>> print(inner_planets[7])
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    print(inner_planets[7])
IndexError: list index out of range
>>> # print list times index 0 to 2. 
>>> Note in index slicing, the last index item is never printed. 
>>> It is always one less than specified in the statement.
>>> print(inner_planets[0 : 2])
['mercury', 'venus']
>>> print(inner_planets[0:3])
['mercury', 'venus', 'earth']
>>> # You can also specify the index without using print function.
>>> inner_planets[0:2]
['mercury', 'venus']
>>>

Note 1:  In index slicing like [2:4], index 4 is never printed.

Note 2: Python gives a syntax error if the index specified is out of range., that is if the list has index 0 to 3 and the statement specifies index = 5, Python gives a syntax error.

Lists: Change items, add items, removal of items

As mentioned in the section above, unlike strings, which are immutable, lists, on the other hand, are a mutable type. Thus, it is possible to change the items in the list. Therefore, lists are more versatile.  You can add, delete, or make changes to the list.  These operations will be difficult to do in strings.

Changing items in a list

Let us now see how we can make changes to the list ‘inner_planets’.  Note that the first letter of the items on the planet names in the inner_planet lists is lowercase. We will write a program to capitalize the first letter ‘m’ in ‘mercury’ to ‘M’.  We will use an index number corresponding to mercury. The index number for mercury is 0 since it is the first item.

PROGRAM EXAMPLE: MAKING CHANGES TO THE LIST
>>> # Programs to change items in list
>>> inner_planets = ['mercury','venus','earth','mars']
>>> # Capitalize the first letter of planet mercury.
>>> inner_planets[0] = 'Mercury'
>>> # Now let’s check if the first letter 'm' in mercury got changed to 'M'
>>> inner_planets
['Mercury', 'venus', 'earth', 'mars']
>>>

Replace items in a list

Any item in a list can be replaced by a new item by pointing to the item’s index.

The program below has two examples.

1) a list containing letters and

2) a list containing digits.

For the first example, will use the list called “inner_planets” and replace the item “earth” (index = 2) with the text “planet we live on”.

In the second example, we will use the number_list [1, 2, 3, 4] and replace ‘2’ (index = 1) with the digits “200”. Finally, we will replace the number “200” with the text “two hundred”.

PROGRAM EXAMPLE: REPLACING ITEM IN A LIST BY ANOTHER ITEM
>>> # Replace an item by another item
>>> inner_planets = ['mercury','venus','earth','mars']
>>> inner_planets
['mercury', 'venus', 'earth', 'mars']
>>> # earth is at index = 2.  use index = 2 to replace 'earth' by 'planet we live on'
>>> inner_planets[2] = 'planet we live on'
>>> # Check if item 'earth' was replaced by 'planet we live on'
>>> inner_planets
['mercury', 'venus', 'planet we live on', 'mars']
>>> 
>>> 
>>> # Replace an item in list composed of digits
>>> number_list = [1, 2, 3, 4]
>>> # replace '2' by '200'
>>> number_list[1] = 200
>>> # Check the result.
>>> number_list
[1, 200, 3, 4]
>>> 
>>> # Next we will replace digits '200' by string 'two hundred'.
>>> number_list[1] = 'two hundred'
>>> # Now we check the result of replacement.
>>> number_list
[1, 'two hundred', 3, 4]
>>> 

Delete items in a list

Occasionally, there are situations where you may like to delete items from the list.  The index of the item to be deleted is used to select the item to be deleted.

In the program below, we will delete ‘mercury’ and ‘venus’ from the list.

Recall list [] is an empty list. We will use the empty list [] to delete items mercury and venus (index 0 and 1).

PROGRAM EXAMPLE: ITEM DELETION IN A LIST
>>> inner_planets = ['mercury','venus','earth','mars']
>>> inner_planets # Print the inner_planets list
['mercury', 'venus', 'earth', 'mars']
>>> # Now delete mercury and venus from the list
>>> inner_planets[0:2] = []
>>> # Check if mercury and venus got deleted
>>> inner_planets
['earth', 'mars']

The Delete (del) Statement

The del statement can be used to delete an item from the list by using the item’s index. In the example below, we define a list named number_list = [1, ‘two hundred’, 3, 4].  We use the index of item ‘two hundred’ to delete ‘two hundred’ from the list using the del statement. Note the Index for ‘two hundred’ is 1.

PROGRAM EXAMPLE: DELETE (del) STATEMENT TO DELETE ITEMS IN THE LIST
>>> number_list = [1, 'two hundred', 3, 4]
>>> # We will use del statement to remove 'two hundred' from the list.
>>> del number_list[1]
>>> # Now check if del statement deleted item 'two hundred' from the list
>>> number_list
[1, 3, 4]
>>> 

The del statement can also be used to remove many items (slices) from the list.  If you want to clear the entire list, the del statement can also be used to clear the entire list.

We again start with a list called number_list = [1, ‘two hundred’, 3, 4]. We will delete list items ‘two hundred’ and 3 (index 1 and 2) from the list using the del statement.

Next, we will use the del statement to delete the entire list.

PROGRAM EXAMPLE: DELETE THE ENTIRE LIST
>>> # Define number_list
>>> number_list = [1, 'two hundred', 3, 4]
>>> # We will delete a slice index [1:3] ('two hundred', 3) from the list using del statement.
>>> del number_list[1:3]
>>> # Now check if 'two hundred' and 3 have been deleted.
>>> number_list
[1, 4]
>>> 
>>> # Now let us see if we can delete the entire list using del statement.
>>> del number_list[:]
>>> # now check to see if number_list is empty.
>>> number_list
[]     # Empty list
>>>

In the above example, number_list is an empty list [].

If instead, you use statement del number_list, the ‘number_list’ variable is deleted. In the program below, the variable ‘number_list’ does not exist anymore.

PROGRAM EXAMPLE: DELETE (del) COMMAND TO DELETE THE LIST VARIABLE
>>> del number_list
>>> number_list
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    number_list
NameError: name 'number_list' is not defined

Add items in a list

You could also add an item to the list.  This can be done by using plus (+) symbol. 

  1. In the program below, we will use a list made out of the digits [1, 2, 3, 4].
  2. In the second part of the program, we will add items to a list made out of words.  Continuing with our solar system theme, we will add an item ‘asteroid’ to the list.

Asteroid Facts:

The solar system has eight planets, namely, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, and Neptune in this order. In between Mars orbit and Jupiter orbit, there are hundreds of thousands of small rocks orbiting the Sun.  These rocks are known as the asteroid belt. There are only around 200 known asteroids that exceed 100 km in diameter, making the majority of the asteroids relatively small objects. Some of these asteroid rocks may reach other planets. It is believed that an asteroid’s impact on earth around 65 million years ago caused a chain reaction that led to the extinction of the dinosaurs and affected all life on Earth, according to scientists. In the program below, we will add the item ‘asteroid’ to the ‘inner_planet’ list.

PROGRAM EXAMPLE: ADDING ITEMS TO THE LIST
>>> number_list = [1, 2, 3, 4]
>>> # Add the number '5' to the list.
>>> # Define a new list called ‘number_list2’.
>>> number_list2 = number_list + [5]
>>> # Check if '5' got added to the list
>>> number_list2
[1, 2, 3, 4, 5]
>>> 
>>> # Let us now add 'asteroid' to the inner_planets list.
>>> inner_planets = ['mercury','venus','earth','mars']
>>> inner_planets + ['asteroid']
['mercury', 'venus', 'earth', 'mars', 'asteroid']
>>> 

Append items to a list

We can add new items to a list at the end of the list. This is done by using the ‘appendmethod. There are several methods associated with the list data type. Methods will be introduced on the Python Module page.

PROGRAM EXAMPLE: APPEND ITEMS TO THE LIST
>>> # We will use append method to add number 5 to the list [1, 2, 3, 4]
>>> number_list = [1, 2, 3, 4]
>>> number_list.append(5)
>>> number_list
[1, 2, 3, 4, 5]
>>> 
>>> # Now we will add jupiter to the inner_planet list
>>> inner_planets = ['mercury','venus','earth','mars'] # Define inner_planets list.
>>> # Now use append method to append jupiter to the inner_planets list.
>>> inner_planets.append('jupiter')
>>> # Now check if jupiter got appended to the inner_planets list
>>> inner_planets
['mercury', 'venus', 'earth', 'mars', 'jupiter']
>>>

Mixed Lists

Lists can contain text, numbers and symbols.  Here is an example.

Mixed_list = [‘sun’, ‘is’, 90, ‘million’, ‘miles’, ‘from’, ‘earth’, ‘!!’]

PROGRAM EXAMPLE: LIST CONTAINING STRINGS AND INTEGERS
>>> mixed_list = ['sun', 'is', 90, 'million', 'miles', 'from', 'earth']
>>> print(mixed_list)
['sun', 'is', 90, 'million', 'miles', 'from', 'earth']
>>>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Verified by MonsterInsights