Operations on Sub-Lists

Introduction

Lists support various types of operations. We have already been introduced to some of them such as the ability to derive a sub-list from an existing list. Other operations are available.

Practical LearningPractical Learning: Introducing Lists

  1. Start Visual Studio Code
  2. On the main menu, click File -> New File
  3. Click the Select A Language link
  4. Scroll down in the list of languages and click Python (python)
  5. In the empty document, type the following lines:
    employee = [ 395723, "Sergio", "Wells", 22.25, 6.5, 7.5,  6, 7.5, 6 ]
    
    empl_identification = employee[:4]
    time_summary        = employee[-5:]
        
    empl_name   = empl_identification[1] + " " + empl_identification[2]
    time_worked = time_summary[0] + time_summary[1] + time_summary[2] + time_summary[3] + time_summary[4]
    net_pay     = empl_identification[3] * time_worked
        
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:    {empl_identification[0]}")
    print(F"Employee Name: {empl_name}")
    print(f"Hourly Salary: {empl_identification[3]:5.2f}")
    print("==============================================")
    print("Time Worked")
    print("----------------------------------------------")
    print(f"Monday:       {time_summary[0]:5.2f}")
    print(f"Tuesday:      {time_summary[1]:5.2f}")
    print(f"Wednesday:    {time_summary[2]:5.2f}")
    print(f"Thursday:     {time_summary[3]:5.2f}")
    print(f"Friday:       {time_summary[4]:5.2f}")
    print("----------------------------------------------")
    print(F"Total Time:    {time_worked:5.2f}")
    print(F"Net Pay:       {net_pay:6.2f}")
    print("==============================================")
  6. To save the document, on the main menu, click File -> Save
  7. Select a folder of your choice or create one and select it in the top combo box of the dialog box
  8. Change the File Name to Exercise17
  9. Click Save
  10. To execute the application to make sure it is working, on the main menu, click Run -> Run Without Debugging
    ==============================================
        - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    395723
    Employee Name: Sergio Wells
    Hourly Salary: 22.25
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        6.50
    Tuesday:       7.50
    Wednesday:     6.00
    Thursday:      7.50
    Friday:        6.00
    ----------------------------------------------
    Total Time:    33.50
    Net Pay:       745.38
    ==============================================

The Mutability of a List

In Python programming, lists are mutable. This characteristic of lists allows you to change the value of an element of a list. To do this, access the item by its index and assign the new value to it. Here are two examples:

floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera", "Smartphone"  ]

print("All Lists")
print('------------------------------------------------------')
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print('-----------------------------------------------------------------------------------------------')

# Replacing the third item
floats[2] = 38.50
# Replacing the fourth item
types_of_cameras[3] = 'Instant'

print("Items Replacement")
print('------------------')
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print('================================================================================================')

This would produce:

All Lists
------------------------------------------------------
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera', 'Smartphone']
-----------------------------------------------------------------------------------------------
Items Replacement
------------------
Decimal Numbers:  [32.0, 44.5, 38.5, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant', 'Smartphone']
================================================================================================
Press any key to continue . . .

Practical LearningPractical Learning: Updating the Items of a List

  1. Change the document as follows:
    employee = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Enter Employee Information")
    print("----------------------------------------------")
    employee[0] = input("Employee #:    ")
    employee[1] = input("First Name:    ")
    employee[2] = input("Last Name:     ")
    employee[3] = float(input("Hourly Salary: "))
    print("==============================================")
    print("Enter the time worked for each day")
    print("----------------------------------------------")
    employee[4] = float(input("Monday:       "))
    employee[5] = float(input("Tuesday:      "))
    employee[6] = float(input("Wednesday:    "))
    employee[7] = float(input("Thursday:     "))
    employee[8] = float(input("Friday:       "))
    
    empl_name   = employee[1] + " " + employee[2]
    time_worked = employee[-5] + employee[-4] + employee[-3] + employee[-2] + employee[-1]
    net_pay     = employee[3] * time_worked
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:    {employee[0]}")
    print(F"Employee Name: {empl_name}")
    print(f"Hourly Salary: {employee[3]:5.2f}")
    print("==============================================")
    print("Time Worked")
    print("----------------------------------------------")
    print(f"Monday:       {employee[-5]:5.2f}")
    print(f"Tuesday:      {employee[-4]:5.2f}")
    print(f"Wednesday:    {employee[-3]:5.2f}")
    print(f"Thursday:     {employee[-2]:5.2f}")
    print(f"Friday:       {employee[-1]:5.2f}")
    print("----------------------------------------------")
    print(F"Total Time:    {time_worked:5.2f}")
    print(F"Net Pay:       {net_pay:6.2f}")
    print("==============================================")
  2. To execute, on the main menu, click Run -> Run Without Debugging
  3. In the Terminal window, where the pieces of information are requested, click the on the right side of Employee #, type to 748407 and press Enter
  4. For the First Name, type to Maria and press Enter
  5. For the Last Name, type to Garland and press Enter
  6. For the Hourly Salary, type to 30.05 and press Enter
  7. For Monday, Tuesday, Wednesday, Thursday, and Friday, type to 8 and press Enter for each
    ==============================================
            - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    748407
    Employee Name: Maria Garland
    Hourly Salary: 30.05
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        8.00
    Tuesday:       8.00
    Wednesday:     8.00
    Thursday:      8.00
    Friday:        8.00
    ----------------------------------------------
    Total Time:    40.00
    Net Pay:       1202.00
    ==============================================
  8. Change the document as follows:
    empl_972950 = [ 972950, 'Frank',   'Milans',  20.05,  7.00, 6.00,  8.50, 7.50,  6.50 ]
    empl_495826 = [ 495826, "Shannon", 'Ladd',    15.68,  8.50, 9.50, 10.00, 8.00,  9.50 ]
    empl_293844 = [ 293844, "Garry"    'Whitlow', 17.59,  8.00, 7.50,  8.00, 8.00,  7.00 ]
    empl_748407 = [ 748407, 'Maria',   "Garland", 30.05,  8.00, 8.00,  8.00, 8.00,  8.00 ]
    empl_395723 = [ 395723, "Sergio",  "Wells",   22.25,  6.50, 7.50,  6.00, 7.50,  6.00 ]
    empl_638471 = [ 638471, "Justine", "Larson",  28.47, 10.50, 9.00,  8.50, 8.50, 10.00 ]
        
    time_worked = empl_638471[4] + empl_638471[5] + empl_638471[6] + empl_638471[7] + empl_638471[8]
    net_pay     = empl_638471[3] * time_worked
        
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:       {empl_638471[0]}")
    print(F"Employee Name:    {empl_638471[1]} {empl_638471[2]}")
    print(f"Hourly Salary: {empl_638471[3]:8.2f}")
    print("==============================================")
    print("Time Worked")
    print("----------------------------------------------")
    print(f"Monday:       {empl_638471[4]:8.2f}")
    print(f"Tuesday:      {empl_638471[5]:8.2f}")
    print(f"Wednesday:    {empl_638471[6]:8.2f}")
    print(f"Thursday:     {empl_638471[7]:8.2f}")
    print(f"Friday:       {empl_638471[8]:8.2f}")
    print("----------------------------------------------")
    print(F"Total Time:    {time_worked:8.2f}")
    print(F"Net Pay:       {net_pay:8.2f}")
    print("==============================================")
  9. To execute the application to make sure it is working, on the main menu, click Run -> Run Without Debugging
    ==============================================
            - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:       638471
    Employee Name:    Justine Larson
    Hourly Salary:    28.47
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:           10.50
    Tuesday:           9.00
    Wednesday:         8.50
    Thursday:          8.50
    Friday:           10.00
    ----------------------------------------------
    Total Time:       46.50
    Net Pay:        1323.86
    ==============================================

Replacing a Sub-List

To replace a group of items in a list, you can replace one at a time as we saw above. If the items you want to replace are in a range, you can first obtain the range using any of the techniques we learned already, then assign the new value or the new list to it. The replacing item(s) must be provided as a list. Consider the following examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera" ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95 ]

print("All Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print(f"Types of cameras:", types_of_cameras)
print('---------------------------------------------------------------------------------')
print("Sub-Lists")
print('------------------------------------------------------')
print("Some Type of List:      ", naturals[:-2])
print("3rd, 4ty, and 5th Items:", floats[2:5])
print("1st, 2nd, and 3rd items:", pay_rates[0:3])
print("First Type of camera:   ", types_of_cameras[0:-3])
print("Last Type of camera:    ", types_of_cameras[3:100])
print('================================================================================')

# Replace the first three natural numbers by a string
naturals[:-2] = ['Distances']
# Replace the 3rd, 4ty, and 5th items of the list
floats[2:5] = [808.88, 1039.86, 75.95]
# Replace the 1st, the 2nd, and the  3rd items of a list
pay_rates[0:3] = ['Hourly Salary:']
# Replace the first item in the list
types_of_cameras[0:-3] = [ "Disposable"]
# Replace the last item in the list
types_of_cameras[3:11] = [ "Instant Operation"]

print("New List with Replacements")
print('------------------------------------------------------')
print('Highway Administration:', naturals)
print("Decimal Numbers:       ", floats)
print("Hourly Salaries:       ", pay_rates)
print(f"Types of cameras:      ", types_of_cameras)
print('================================================================================')

This would produce:

All Items
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera']
---------------------------------------------------------------------------------
Sub-Lists
------------------------------------------------------
Some Type of List:       [29, 7594, 3708]
3rd, 4ty, and 5th Items: [35.0, 42.0, 48.5]
1st, 2nd, and 3rd items: [15.55, 30.05, 24.8]
First Type of camera:    ['Point of Shoot']
Last Type of camera:     ['Instant (Polaroid) Camera']
================================================================================
New List with Replacements
------------------------------------------------------
Highway Administration: ['Distances', 5050, 684]
Decimal Numbers:        [32.0, 44.5, 808.88, 1039.86, 75.95, 35.0]
Hourly Salaries:        ['Hourly Salary:', 17.95]
Types of cameras:       ['Disposable', 'DSLR', '360', 'Instant Operation']
================================================================================
Press any key to continue . . .

Fundamental Operations on Lists

Nullifying the Value of an Item

If you don't want an element of a list to continue having any value at all, you can remove that value. To do that, access the item by its index and assign empty square brackets to it. When you do this, you are not removing the item, you are only removing its value. This means that the item would keep its position but would not have a valid value. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera" ]

print("All Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print(f"Types of cameras:", types_of_cameras)
print('---------------------------------------------------------------------------------')

# Nullifying the first item of the list
naturals[0] = []
# Nullifying the secoond item of the list
floats[1]   = []
# Nullifying the last item of the list
types_of_cameras[-1] = []

print("Lists with some nullified items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print(f"Types of cameras:", types_of_cameras)
print('================================================================================')

This would produce:

All Items
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera']
---------------------------------------------------------------------------------
Lists with some nullified items
------------------------------------------------------
Natural Numbers:  [[], 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, [], 35.0, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360', []]
================================================================================
Press any key to continue . . .

Deleting an Item of a List

In a list, if you have an item you don't want any more, you can remove that item. To perform this operation, you can use an operator or keyword named del. To use it, type del followed by an item of a list (we have already seen how to locate an item based on its index. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera"  ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95 ]

print("Lists of Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print("Hourly Salaries: ", pay_rates)
print('---------------------------------------------------------------------------------')

# Delete the first item
del naturals[0]
# Delete the second item
del floats[1]
# Delete the last item
del types_of_cameras[-1]
# Delete the second from last
del pay_rates[-2]

print("Lists of Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print("Hourly Salaries: ", pay_rates)
print('================================================================================')

This would produce:

Lists of Items
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera']
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95]
---------------------------------------------------------------------------------
Lists of Items
------------------------------------------------------
Natural Numbers:  [7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 35.0, 42.0, 48.5, 35.0]
Types of cameras: ['Point of Shoot', 'DSLR', '360']
Hourly Salaries:  [15.55, 30.05, 17.95]
================================================================================
Press any key to continue . . .

Removing a Sub-List

We have already learned various ways to create a sub-list from an existing list. To delete a sub-list, type the del operator/keyword followed by the sub-list. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95, 32.15, 9.98, 22.25 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant Camera", "Smartphone"  ]

print("All Items")
print('------------------------------------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print("Types of cameras:", types_of_cameras)
print('------------------------------------------------------------------------------------')

print("Sub-Lists")
print('--------------------------------------------------------------------')
print("First two items:                          ", naturals[0:2])
print("Second, third, and fourth items:          ", floats[1:4])
print("From the third item to two items from end:", pay_rates[2:-2])
print("Two items from last, excluding the last:  ", types_of_cameras[2:-1])
print('--------------------------------------------------------------------')

# Delete first two items
del naturals[0:2]
# Delete second, third, and fourth items
del floats[1:4]
# Delete the third item to two items from end
del pay_rates[2:-2]
# Delete the two items from the last, excluding the last item
del types_of_cameras[2:-1]

print("Items after some deletions")
print('---------------------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print("Types of cameras:", types_of_cameras)
print('====================================================================')

This would produce:

All Items
------------------------------------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95, 32.15, 9.98, 22.25]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant Camera', 'Smartphone']
------------------------------------------------------------------------------------
Sub-Lists
--------------------------------------------------------------------
First two items:                           [29, 7594]
Second, third, and fourth items:           [44.5, 35.0, 42.0]
From the third item to two items from end: [24.8, 17.95, 32.15]
Two items from last, excluding the last:   ['360', 'Instant Camera']
--------------------------------------------------------------------
Items after some deletions
---------------------------------------------------------------------
Natural Numbers:  [3708, 5050, 684]
Decimal Numbers:  [32.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 9.98, 22.25]
Types of cameras: ['Point of Shoot', 'DSLR', 'Smartphone']
====================================================================
Press any key to continue . . .

Clearing a List

Clearing a list consists of removing all its items. If a list is stored in a variable, you can clear that list while keeping the variable as an object. To clear a list, simply assign empty square brackets to it. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera"  ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95 ]

print("Lists of Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print(f"Types of cameras:", types_of_cameras)
print('---------------------------------------------------------------------------------')

# Resetting the lists
naturals = []
floats   = []
types_of_cameras = []
pay_rates = []

print("Emptiness")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print(f"Types of cameras:", types_of_cameras)
print('================================================================================')

This would produce:

Lists of Items
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera']
---------------------------------------------------------------------------------
Emptiness
------------------------------------------------------
Natural Numbers:  []
Decimal Numbers:  []
Hourly Salaries:  []
Types of cameras: []
================================================================================
Press any key to continue . . .

List-Based Operations

Adding a List to a List

You can add one list to another list. This operation is very simple: apply the + operator between two lists, between a list and a variable that holds a list or vice-versa, or between two variables that each holds a list. The addition produces a new list with the items from the left list first followed by the items from the second list. Here is an example:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95, 9.98, 22.25 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera", "Smartphone" ]

new_list = pay_rates + types_of_cameras

print("All Lists")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print("Types of cameras:", types_of_cameras)
print('-----------------------------------------------------------------------------------------------')
print("List Addition")
print('------------------')
print("Pay Rates + Types of Cameras:", new_list)
print('================================================================================================')

This would produce:

All Lists
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95, 9.98, 22.25]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera', 'Smartphone']
-----------------------------------------------------------------------------------------------
List Addition
------------------
Pay Rates + Types of Cameras: [15.55, 30.05, 24.8, 17.95, 9.98, 22.25, 'Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera', 'Smartphone']
================================================================================================
Press any key to continue . . .

Adding an Item to a List

The addition operator allows you to add an item to a list, but you must present that item as a its own list; that is, you must include that item in square brackets. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 32.00, 44.50, 35.00, 42.00, 48.50, 35.00 ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95, 9.98, 22.25 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360", "Instant (Polaroid) Camera", "Smartphone" ]

times_worked = floats + [40.00]
distances = [ 'Distances:' ] + naturals

print("All Lists")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Hourly Salaries: ", pay_rates)
print("Types of cameras:", types_of_cameras)
print('-----------------------------------------------------------------------------------------------')
print("List Addition")
print('------------------')
print("Times Worked:", times_worked)
print(distances)
print('================================================================================================')

This would produce:

All Lists
------------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [32.0, 44.5, 35.0, 42.0, 48.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95, 9.98, 22.25]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera', 'Smartphone']
-----------------------------------------------------------------------------------------------
List Addition
------------------
Times Worked: [32.0, 44.5, 35.0, 42.0, 48.5, 35.0, 40.0]
['Distances:', 29, 7594, 3708, 5050, 684]
================================================================================================
Press any key to continue . . .

In the same way, you can add individual items one at a time, as long as you include each new item in its own square brackets.

As mentioned previously, the addition operation produces a new list. Once you have that new list, you can access any item, you can get a sub-list from it, and you can perform any appropriate operation on the item(s).

A List in a List

Introduction to Nesting a List

So far, the items of our list were numbers and strings. An item of a list can be almost any type of value. In fact, an item of a list can be its own list. This means that a list can be nested inside another list. To make this happen, in the placeholder of an item, create a list. The main or primary list is the parent or nesting list. The list included is referred to as child or nested. Here are examples of child or nested lists:

work_summary = [ "Payroll", [22.38, 39.50], 'Pay Supervisor', [25.85, 44.50], [18.25, 40.00] ]

print("Work Summary: ", work_summary)
print('==========================================================================================')

This would produce:

Work Summary:  ['Payroll', [22.38, 39.5], 'Pay Supervisor', [25.85, 44.5], [18.25, 40.0]]
==========================================================================================
Press any key to continue . . .

Practical LearningPractical Learning: Nesting Some Lists

Accessing Individual Lists

As seen already, each item of a list occupies a position. In the same way, if you create a list inside a list, the nested list occupies its own position. You can access a nested using its position or index, using an index as we have seen them so far. Here are examples:

work_summary = [ "Payroll", [22.38, 39.50], 'Pay Supervisor', [25.85, 44.50], [18.25, 40.00] ]

print("Work Summary: ", work_summary)
print('------------------------------------------------------------------------------------------')
print("   Title:                        ", work_summary[0])
print("1. Hourly Salary and time worked:", work_summary[1])
print("   Manager:                      ", work_summary[2])
print("2. Hourly Salary and time worked:", work_summary[3])
print("3. Hourly Salary and time worked:", work_summary[4])
print('==========================================================================================')

This wouold produce:

Work Summary:  ['Payroll', [22.38, 39.5], 'Pay Supervisor', [25.85, 44.5], [18.25, 40.0]]
------------------------------------------------------------------------------------------
   Title:                         Payroll
1. Hourly Salary and time worked: [22.38, 39.5]
   Manager:                       Pay Supervisor
2. Hourly Salary and time worked: [25.85, 44.5]
3. Hourly Salary and time worked: [18.25, 40.0]
==========================================================================================
Press any key to continue . . .

Accessing the Items of a Nested List

Once you have accessed an item that is a nested list, you can access an item of that child list by applying new square brackets to the accessed child list. The first item of the child list has Index 0, the second has Index 1, the third item, if any, has Index 2, and so on. Here are examples:

work_summary = [ "Payroll", [22.38, 39.50], 'Pay Supervisor',
                 ['Webmaster', 25.85, 44.50],
                 ['Michael', 'Carlock', 18.25, 40.00]
               ]

print("Work Summary: ", work_summary)
print('------------------------------------------------------------------------------------------')
print("    Title:        ", work_summary[0])
print('----------------------------------')
print("1a. Hourly Salary:", work_summary[1][0])
print("1b. Time Worked:  ", work_summary[1][1])
print('----------------------------------')
print("    Manager:      ", work_summary[2])
print('----------------------------------')
print("2a. Job Title:    ", work_summary[3][0])
print("2b. Hourly Salary:", work_summary[3][1])
print("2c. Time Worked:  ", work_summary[3][2])
print('----------------------------------')
print("3a. First Name:   ", work_summary[4][0])
print("3b. Last Name:    ", work_summary[4][1])
print("3c. Hourly Salary:", work_summary[4][2])
print("3d. Time Worked:  ", work_summary[4][3])
print('==========================================================================================')

This would produce:

Work Summary:  ['Payroll', [22.38, 39.5], 'Pay Supervisor', ['Webmaster', 25.85, 44.5], ['Michael', 'Carlock', 18.25, 40.0]]
------------------------------------------------------------------------------------------
    Title:         Payroll
----------------------------------
1a. Hourly Salary: 22.38
1b. Time Worked:   39.5
----------------------------------
    Manager:       Pay Supervisor
----------------------------------
2a. Job Title:     Webmaster
2b. Hourly Salary: 25.85
2c. Time Worked:   44.5
----------------------------------
3a. First Name:    Michael
3b. Last Name:     Carlock
3c. Hourly Salary: 18.25
3d. Time Worked:   40.0
==========================================================================================
Press any key to continue . . .

Based on this, you can create a list, as a small database, of values where you have a main list. Inside that list, you can nest values where each sub-list represents a record. This could be done as follows:

work_summary = [ ["Diane",    "Layton",   22.38,  8.00, 6.50, 9.00,  7.50, 8.50],
                 ['Thomas',   'Caldwell', 25.85, 10.00, 8.50, 9.00,  9.50, 7.50],
                 ['Dianne',   'Cozzens',  22.85,  8.00, 6.50, 9.00,  7.50, 6.50],
                 ['Michael',  'Carlock',  18.25,  7.00, 8.50, 6.00,  8.00, 7.00],
                 ['Jennifer', 'Graham',   32.95,  7.50, 8.00, 6.50,  7.00, 8.50],
                 ['Roberta',  'Jenkins',  18.25,  9.00, 7.50, 8.50, 10.00, 8.00],
               ]

You can then access each child list, then access each item of a child list based on its index.

Practical LearningPractical Learning: Ending the Lesson

  1. Change the document as follows:
    employees = [
                    [ 586807, "Diane",   "Layton",  22.38,  8.00,  6.50, 9.00,  7.50,  8.50 ],
                    [ 972950, 'Frank',   'Milans',  20.05,  7.00,  6.00,  8.50, 7.50,  6.50 ],
                    [ 495826, "Shannon", 'Ladd',    15.68,  8.50, 10.50, 10.00, 8.00,  9.50 ]
                ]
    
    time_worked = employees[0][4] + employees[0][5] + employees[0][6] + employees[0][7] + employees[0][8]
    net_pay     = employees[0][3] * time_worked
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:       {employees[0][0]}")
    print(F"Employee Name:    {employees[0][1]} {employees[0][2]}")
    print(f"Hourly Salary: {employees[0][3]:8.2f}")
    print("==============================================")
    print("Time Worked")
    print("----------------------------------------------")
    print(f"Monday:        {employees[0][4]:8.2f}")
    print(f"Tuesday:       {employees[0][5]:8.2f}")
    print(f"Wednesday:     {employees[0][6]:8.2f}")
    print(f"Thursday:      {employees[0][7]:8.2f}")
    print(f"Friday:        {employees[0][8]:8.2f}")
    print("----------------------------------------------")
    print(F"Total Time:    {time_worked:8.2f}")
    print(F"Net Pay:       {net_pay:8.2f}")
    print("==============================================")
  2. To execute the application to make sure it is working, on the main menu, click Run -> Run Without Debugging
    ==============================================
            - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:       586807
    Employee Name:    Diane Layton
    Hourly Salary:    22.38
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:            8.00
    Tuesday:           6.50
    Wednesday:         9.00
    Thursday:          7.50
    Friday:            8.50
    ----------------------------------------------
    Total Time:       39.50
    Net Pay:         884.01
    ==============================================
  3. Close your programming environment

Previous Copyright © 2021-2024, FunctionX Friday 31 December 2021 Next