Introduction to Lists

Overview

So far, when we needed more than one value, we declared as many variables as we wanted. If you have some values and you want to treat them as a one group of values, instead of declaring individual variables for those values, you can create one group for those values. A list is a group of values.

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:
    emplNbr = 972950
    fName   = 'Frank'
    lName   = 'Milans'
    hSal    = 20.05
    mon     = 7
    tue     = 6
    wed     = 8.5
    thu     = 7.5
    fri     = 6.5
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:    {emplNbr}")
    print(F"Employee Name: {fName} {lName}")
    print(f"Hourly Salary: {hSal:5.2f}")
    print("==============================================")
    print("Time Worked")
    print("----------------------------------------------")
    print(f"Monday:       {mon:5.2f}")
    print(f"Tuesday:      {tue:5.2f}")
    print(f"Wednesday:    {wed:5.2f}")
    print(f"Thursday:     {thu:5.2f}")
    print(f"Friday:       {fri:5.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 Exercise16
  9. Click Save
  10. To execute the application and test it, on the main menu, click Run -> Run Without Debugging
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    972950
    Employee Name: Frank Milans
    Hourly Salary: 20.05
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        7.00
    Tuesday:       6.00
    Wednesday:     8.50
    Thursday:      7.50
    Friday:        6.50
    ==============================================

Creating a List

The primary formula to create a list is:

variable-name = [item-1, item-2, item-n];

Start with a name for a variable. The name follows the rules of names of variables. Assign square brackets ([]) to the variable. Inside the square brackets, create a list of values, also called items, also called elements. Those items must be separated by commas. As a starting point, here is an example of a list:

types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]

Practical LearningPractical Learning: Creating a List

Introduction to Accessing a List

After creating a list, you can use it. Probably the simplest way to use a list is to present it to the user. The simplest way to display a list is to pass its name to a print() function. Here is an example:

types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]

print("Types of cameras: ", types_of_cameras)
print('=====================================================')

This would produce:

Types of cameras:  ['Point of Shoot', 'DSLR', '360']
=====================================================
Press any key to continue . . .

Accessing the Members of a List

The Index of an Item from the Start of a List

Every item of a list occupies a specific position. This position is referred to as the index of the item. The first item occupies Position 0, the second item occupies Position 1, the third item occupies Position 2, and so on. This means that the index of the first item is 0, the index of the second item is 1, and so on.

To access an item based on its index from the start of the list, type the name of the variable followed by square brackets. In the square brackets, type the desired index. You can do this in the parentheses of the print() function. Here is an example:

types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]

print("Type of camera:", types_of_cameras[0])
print('=====================================================')

This would produce:

Type of camera: Point of Shoot
=====================================================
Press any key to continue . . .

Practical LearningPractical Learning: Accessing the Items of a List

  1. Change the document as follows:
    employee = [ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ]
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:    {employee[0]}")
    print(F"Employee Name: {employee[1]} {employee[2]}")
    print(f"Hourly Salary: {employee[3]:5.2f}")
    print("==============================================")
  2. To execute the application, on the main menu, click Run -> Run Without Debugging
    ==============================================
        - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    972950
    Employee Name: Frank Milans
    Hourly Salary: 20.05
    ==============================================

The Index of an Item from the End of a List

We mentioned that every item of a list occupies a position known as its index. The index of the last item is -1. Therefore, to get the last item of a list, pass the index as -1. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats   = [ 44.50 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]
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("First Items")
print('------------------------')
print("Natural Number: ", naturals[0])
print("Decimal Number: ", floats[0])
print("Hourly Salary:  ", pay_rates[0])
print(f"Type of camera: ", types_of_cameras[0])
print('=================================')
print("Last Items")
print('-----------------------')
print("Natural Number: ", naturals[-1])
print("Decimal Number: ", floats[-1])
print("Hourly Salary:  ", pay_rates[-1])
print(f"Type of camera: ", types_of_cameras[-1])
print('=================================')

This would produce:

All Items
----------------------------------------------------
Natural Numbers:  [29, 7594, 3708, 5050, 684]
Decimal Numbers:  [44.5]
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95]
Types of cameras: ['Point of Shoot', 'DSLR', '360']
----------------------------------------------------
First Items
------------------------
Natural Number:  29
Decimal Number:  44.5
Hourly Salary:   15.55
Type of camera:  Point of Shoot
====================================================
Last Items
-----------------------
Natural Number:  684
Decimal Number:  44.5
Hourly Salary:   17.95
Type of camera:  360
===================================================
Press any key to continue . . .

As mentioned above, the last item of a list has index -1, the second from last item has index -2, the third from last item has index -3, and so on. Therefore, to get an item, you can use its negative index from the end of the list. 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("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("Items from Start")
print('------------------')
print("First Natural Number:  ", naturals[0])
print("Second Decimal Number: ", floats[1])
print("Third Hourly Salary:   ", pay_rates[2])
print("Fourth Type of camera: ", types_of_cameras[3])
print('=================================================')
print("Items from Last")
print('------------------')
print("Last Natural Number:             ", naturals[-1])
print("Second Decimal Number from Last: ", floats[-2])
print("Third Hourly Salary from Last:   ", pay_rates[-3])
print("Fourth Type of camera from Last: ", types_of_cameras[-4])
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']
--------------------------------------------------------------------------------
Items from Start
------------------
First Natural Number:   29
Second Decimal Number:  44.5
Third Hourly Salary:    24.8
Fourth Type of camera:  Instant (Polaroid) Camera
=================================================
Items from Last
------------------
Last Natural Number:              684
Second Decimal Number from Last:  48.5
Third Hourly Salary from Last:    30.05
Fourth Type of camera from Last:  Point of Shoot
================================================
Press any key to continue . . .

Practical LearningPractical Learning: Accessing the Items from the End of a List

  1. Change the document as follows:
    employee = [ 495826, 'Shannon', 'Ladd', 15.68, 8.5, 9.5, 10, 8, 9.5 ]
    
    print("==============================================")
    print("\t- Payroll Preparation -")
    print("==============================================")
    print("Employee Information")
    print("----------------------------------------------")
    print(f"Employee #:    {employee[0]}")
    print(F"Employee Name: {employee[1]} {employee[2]}")
    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("==============================================")
  2. To execute, on the main menu, click Run -> Run Without Debugging
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    495826
    Employee Name: Shannon Ladd
    Hourly Salary: 15.68
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        8.50
    Tuesday:       9.50
    Wednesday:    10.00
    Thursday:      8.00
    Friday:        9.50
    ==============================================

Arithmetic Operations on Lists

Introduction

When you have accessed an item, you have its value. You can then perform any appropriate operation on it, including arithmetic operations on numbers or operations on strings.

The Addition

The addition is the primary operation in arithmetic. You can perform on items you access by index. After accessing some items by their indexes, you can apply the addition to them, which would result in adding their values.

Other Operations

Although the addition is the most supported operation on lists, if you access an item by it index, you get its value. You then perform any arithmetic operation on the item. For example, you can subtract a constant from an item. You can multiply two items, you can divide an item by a constant, etc. Here are examples:

naturals = [ 29, 7594, 3708, 5050, 684 ]
floats = [ 44.50 ]
types_of_cameras = [ "Point of Shoot", 'DSLR', "360" ]
pay_rates = [ 15.55, 30.05, 24.80, 17.95 ]

addition = naturals[1] + naturals[3]
half     = int(types_of_cameras[2]) / 2
salary   = pay_rates[2] * floats[0]

print("Addition:        ", naturals[1], "+", naturals[3], "=", addition)
print("Half a Number:   ", int(types_of_cameras[2]), "/ 2 =", half)
print("Salary:          ", salary)
print(f"Types of cameras: {types_of_cameras[1]}, "
                        f"{types_of_cameras[0]}, "
                        f"{types_of_cameras[2]}")
print('=====================================================')

This would produce:

Addition:         7594 + 5050 = 12644
Half a Number:    360 / 2 = 180.0
Salary:           1103.6000000000001
Types of cameras: DSLR, Point of Shoot, 360
=====================================================
Press any key to continue . . .

Practical LearningPractical Learning: Performing Arithmetic Operations on Items of a List

  1. Change the document as follows:
    employee = [ 972950, 'Frank', 'Milans', 20.05, 7, 6, 8.5, 7.5, 6.5 ]
    
    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
    ==============================================
            - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    972950
    Employee Name: Frank Milans
    Hourly Salary: 20.05
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        7.00
    Tuesday:       6.00
    Wednesday:     8.50
    Thursday:      7.50
    Friday:        6.50
    ----------------------------------------------
    Total Time:    35.50
    Net Pay:       711.77
    ==============================================

Slicing a List

Introduction

Slicing a list consists of creating a sub-list from an existing list. This is equivalent to isolating or considering a section of a list for any reason you judge necessary. To perform a slicing operation, you combine indices with some special operators.

The primary operator used to slice a list is the colon (:). You include this operator in the square brackets of the list variable. If you simply include the colon in the square brackets, you would get a copy of the whole list of items. 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("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("Natural Numbers: ", 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']
---------------------------------------------------------------------------------
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']
================================================================================
Press any key to continue . . .

The First n Elements of a List

To get the first n elements of a list, put the n number on the right side of the colon. 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("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("First 3 Items")
print('-----------------------------------------------------')
print("Natural Numbers: ", naturals[:3])
print("Decimal Numbers: ", floats[:3])
print("Hourly Salaries: ", pay_rates[:3])
print(f"Types of cameras:", types_of_cameras[:3])
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']
---------------------------------------------------------------------------------
First 3 Items
-----------------------------------------------------
Natural Numbers:  [29, 7594, 3708]
Decimal Numbers:  [32.0, 44.5, 35.0]
Hourly Salaries:  [15.55, 30.05, 24.8]
Types of cameras: ['Point of Shoot', 'DSLR', '360']
================================================================================
Press any key to continue . . .

The Last n Elements of a List

To get the last n elements of a list, put the n number with the negative symbol on the left side of the colon. 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("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("First 3 Items")
print('------------------------------------------------------')
print("Natural Numbers:  ", naturals[:3])
print("Decimal Numbers:  ", floats[:3])
print("Hourly Salaries:  ", pay_rates[:3])
print(f"Types of cameras: ", types_of_cameras[:3])
print('================================================================================')
print("Last 3 Items")
print('-----------------------------------------------------')
print("Natural Numbers:  ", naturals[-3:])
print("Decimal Numbers:  ", floats[-3:])
print("Hourly Salaries:  ", pay_rates[-3:])
print(f"Types of cameras: ", types_of_cameras[-3:])
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']
---------------------------------------------------------------------------------
First 3 Items
------------------------------------------------------
Natural Numbers:   [29, 7594, 3708]
Decimal Numbers:   [32.0, 44.5, 35.0]
Hourly Salaries:   [15.55, 30.05, 24.8]
Types of cameras:  ['Point of Shoot', 'DSLR', '360']
================================================================================
Last 3 Items
-----------------------------------------------------
Natural Numbers:   [3708, 5050, 684]
Decimal Numbers:   [42.0, 48.5, 35.0]
Hourly Salaries:   [30.05, 24.8, 17.95]
Types of cameras:  ['DSLR', '360', 'Instant (Polaroid) Camera']
===============================================================================
Press any key to continue . . .

Practical LearningPractical Learning: Introducing Sub-Lists

  1. Change the document as follows:
    employee = [ 293844, "Garry", "Whitlow", 17.59, 8.00, 7.50,  8.00, 8.00, 7.00 ]
    
    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("==============================================")
  2. To execute, on the main menu, click Run -> Run Without Debugging
    ==============================================
            - Payroll Preparation -
    ==============================================
    Employee Information
    ----------------------------------------------
    Employee #:    293844
    Employee Name: Garry Whitlow
    Hourly Salary: 17.59
    ==============================================
    Time Worked
    ----------------------------------------------
    Monday:        8.00
    Tuesday:       7.50
    Wednesday:     8.00
    Thursday:      8.00
    Friday:        7.00
    ----------------------------------------------
    Total Time:    38.50
    Net Pay:       677.22
    ==============================================

Excluding the Last n Elements of a List

To get the list of items without the last n items, write the negative n number on the right side of the colon. 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("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("Excluding the last 2 Items")
print('------------------------------------------------------')
print("Natural Numbers:  ", naturals[:-2])
print("Decimal Numbers:  ", floats[:-2])
print("Hourly Salaries:  ", pay_rates[:-2])
print(f"Types of cameras: ", types_of_cameras[:-2])
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']
---------------------------------------------------------------------------------
Excluding the last 2 Items
------------------------------------------------------
Natural Numbers:   [29, 7594, 3708]
Decimal Numbers:   [32.0, 44.5, 35.0, 42.0]
Hourly Salaries:   [15.55, 30.05]
Types of cameras:  ['Point of Shoot', 'DSLR']
================================================================================

A Sub-List from Start

You can combine the index and the colon operator (:) to create a sub-list. Start by including a colon (:) in the square brackets. To specify that you want the sub-list to start from the beginning of the list, which is Index 0, write the desired positive index on the left of the colon (:). For example, to get all items, use 0:. To get all items excluding the first, specify the index as 1:, to get the items excluding the first two, specify the index as 2:, and so on. 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, 9.98, 22.25 ]

print("All Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print("Hourly Salaries: ", pay_rates)
print('--------------------------------------------------------------------------------')
print("Items from Start")
print('------------------')
print("Whole list from First:          ", naturals[0:])
print("Excluding First Item:           ", floats[1:])
print("List Excluding First Two:       ", types_of_cameras[2:])
print("List Excluding First Three:     ", pay_rates[3:])
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']
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95, 9.98, 22.25]
--------------------------------------------------------------------------------
Items from Start
------------------
Whole list from First:           [29, 7594, 3708, 5050, 684]
Excluding First Item:            [44.5, 35.0, 42.0, 48.5, 35.0]
List Excluding First Two:        ['360', 'Instant (Polaroid) Camera']
List Excluding First Three:      [17.95, 9.98, 22.25]
===============================================================================
Press any key to continue . . .

A Sub-List from End

Remember that, if you use the colon operator on a list, the index of the last item is negative one (-1). To create a sub-list from the end of a list, write a negative index on the right side of the colon operator. Based on this, to get a list of items without the last item, set the index as :-1. To get a list that excludes the last two items, specify the index as :-2; to get the list without the last three item, type the index as -2, and so on. 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, 9.98, 22.25 ]

print("All Items")
print('------------------------------------------------------')
print("Natural Numbers: ", naturals)
print("Decimal Numbers: ", floats)
print("Types of cameras:", types_of_cameras)
print("Hourly Salaries: ", pay_rates)
print('--------------------------------------------------------------------------------')
print("Items from Start")
print('------------------')
print("Whole list from First:          ", naturals[0:])
print("Excluding First Item:           ", floats[1:])
print("List Excluding First Two:       ", types_of_cameras[2:])
print("List Excluding First Three:     ", pay_rates[3:])
print('======================================================')
print("Items from Last")
print('------------------')
print("List Without Last Element:      ", naturals[:-1])
print("Excluding Last Two Items:       ", floats[:-2])
print("List Excluding Last Three Items:", types_of_cameras[:-3])
print("List Without Last Four Items:   ", pay_rates[:-4])
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']
Hourly Salaries:  [15.55, 30.05, 24.8, 17.95, 9.98, 22.25]
--------------------------------------------------------------------------------
Items from Start
------------------
Whole list from First:           [29, 7594, 3708, 5050, 684]
Excluding First Item:            [44.5, 35.0, 42.0, 48.5, 35.0]
List Excluding First Two:        ['360', 'Instant (Polaroid) Camera']
List Excluding First Three:      [17.95, 9.98, 22.25]
======================================================
Items from Last
------------------
List Without Last Element:       [29, 7594, 3708, 5050]
Excluding Last Two Items:        [32.0, 44.5, 35.0, 42.0]
List Excluding Last Three Items: ['Point of Shoot']
List Without Last Four Items:    [15.55, 30.05]
=======================================================
Press any key to continue . . .

A Sub-List from a Range

All the sub-lists we have created so far were considering the extreme sides of a list, the beginning or the end of the list. In some cases, you want to create a sub-list that includes items from a certain index to anther index. To do this, you use both sides of the colon operator (:) to specify the range. Remember that from the beginning of a list. The number on the left side of the colon will represent the index from where to start the range, using 0 as the starting index. The number on the right side of the colon is also an index but, this time, the index starts at 1. Based on this, if you write the right-side index as 1, it would represent the first item from left, if you write the right side index as 2, it would represent the second item from the beginning. 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"  ]

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("Items from Start")
print('------------------')
print("Empty List:                                        ", naturals[0:0])
print("From the beginning of the list, add one item:       ", floats[0:1])
print("From the beginning of the list to the second item:  ", pay_rates[0:2])
print("From the second item of the list to the third item:", types_of_cameras[1:4])
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, 9.98, 22.25]
Types of cameras: ['Point of Shoot', 'DSLR', '360', 'Instant (Polaroid) Camera', 'Smartphone']
-----------------------------------------------------------------------------------------------
Items from Start
------------------
Empty List:                                         []
From the beginning of the list, add one item:        [32.0]
From the beginning of the list to the second item:   [15.55, 30.05]
From the second item of the list to the third item: ['DSLR', '360', 'Instant (Polaroid) Camera']
================================================================================================
Press any key to continue . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2024, FunctionX Friday 10 September 2021 Next