Lesson 3 - Lists basics

  • Python List

    Python has a great built-in data type named “list”. List elements are written within square brackets [ ]

    Lists are used to store multiple items in a single variable.

    Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set and Range all with different qualities and usage.

    Example:   
    fruits = ["apple", "orange"," ,"banana"]    # This is a list of Fruits
    subjects = ["maths", "history", "economics","english"]  # This is a list of subjects
    print(Fruits);  print(Subjects)

     

    List Items

    List items are indexed, one can easily access the items in the list using the index.
    The first item has index 0, the second item has index 1 etc.

    Example:
    print(fruits[0]) outputs "apple" 

    print(subjects[2]) outputs "economics"


    Properties of Lists

    These are some of the properties of the lists

    1. Ordered
      Items have defined order, and it will not change unless one manipulates explicitly.
      If you add new items to a list, the new items will be placed at the end of the list.
    2. Changeable
      The list is changeable, meaning that we can change, add, and remove items in a list after it has been created
    3. Allow duplicates
      Lists can have items with the same value,  for example Fruits can have “orange” in index 1 and index 3  etc
    4. Data Types
      List can have elements of different data types.  Ex:     rainPredict  = [“Chicago”, 22.2, True, 2]. 


    List constructor
    It is also possible to use the list() constructor when creating a new list.
    quarter1 = list((“jan”,”feb”,”mar”))    # Note the double rounded braces


    List length
    To find the length of a list, i.e  how many items in the list, use the len() function

    len(fruits) returns 3
    len(subjects) returns 4

    List Access using index
    As explained above, list items are indexed and you can access them with the index number

    fruits = [“apples”, “oranges”, “bananas”, “grapes”, “cherries”]
    fruits[3] returns  grapes


    Negative indexing
    Negative indexing means accessing the list from the end
    -1 refers to the last item, -2 refers to the second last item etc

    fruits[-3] returns bananas

    Range of Indexes
    You can specify a range of indexes by specifying where to start and where to end the range.

    fruits = [“apples”, “oranges”, “bananas”, “grapes”, “cherries”, “kiwi”,  “mangoes”]

    print(fruits[2:4])   outputs  bananas, grapes
    print(fruits[:3])  outputs  apples, oranges, bananas    –  If you leave begin index, first element is taken by default
    print(fruits[4:]) outputs cherries , kiwi, mangoes – –  If you leave end index, first element is taken by default

    Range of Negative Indexes

    Negative indexes are used when  you want to start the search from the end of the list:

    print(thislist[-3:-1])