PYTHON PROGRAMMING. PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS. UNIT 4: LIST

      PYTHON PROGRAMMING

PART II: PYTHON OBJECTS AND DATA STRUCTURE BASICS

UNIT 4: LIST

I. Definition

    Lists are constructed with brackets [] and commas separating every element in the list.

    Assigning a list:

            my_list = [1,2,3]

            list2 = ['string', 1, 5.3]

    len() function tells how many items are in the sequence of the list.

            print(len(my_list))

                => 3

II. Indexing and slicing

    Let:

            my_list = ['one', 'two', 'three', 4, 5]

            print(my_list[0])

                => 'one'

            print(my_list[1:])

                => 'two', 'three', 4, 5

    We can also use '+' to concatenate lists.

            print(list2 + [1,2,3])

                =>  ['string', 1, 5.3, 1, 2, 3]

    Notably, it does not change the original list. To make the change permanent, reassign the list. 

    Furthermore, '*' can be used for a duplication method similar to strings, and of course, it is not permanent.

III. Basic List Methods.

    If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python, however, tend to be more flexible than arrays in other languages for two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).

    Let:

            list1 = [1, 2, 3]

    Use .append() method to permanently add an item to the end of a list.

            print(list1.append(4))

                => [1,2,3,4]

    Use .pop() to "pop off" an item form the list. By default, it pops the last index but you can specify which index to pop off.

            print(list1.pop())

            print(list1)

                => 4

                      [1, 2, 3]

    Of course, an error occurs when a non-exist index is popped.

    You can use .reverse() and .sort() method to affect your lists.

            new_lst = [1,4,5,2,3]

            new_lst.reverse()

            print(new_lst)

            new_lst.sort()

            print(new_lst)

                => [3,2,5,4,1]

                      [1,2,3,4,5]

IV. Nesting lists

    This means we can have lists inside a list.

            lst1 = [1,2,3]

            lst2 = [4,5,6]

            lst3 = [7,8,9]

            matrix = [lst1,lst2,lst3]

            print(matrix)

                [[1,2,3],[4,5,6],[7,8,9]]

    We can actually use indexing here:

            print(matrix[0])

            print(matrix[1][2])

                => [1,2,3]

                      6

V. List Comprehensions

    List Comprehensions allow for quick construction of lists.

            first_col = [row[0] for row in matrix]

            print(first_col)

                => [1,4,7]



Comments