Codecademy Logo

Python Lists

Print Cheatsheet

Lists

In Python, lists are ordered collections of items that allow for easy use of a set of data.

List values are placed in between square brackets [ ], separated by commas. It is good practice to put a space between the comma and the next value. The values in a list do not need to be unique (the same value can be repeated).

Empty lists do not contain any values within the square brackets.

primes = [2, 3, 5, 7, 11] print(primes) empty_list = []

Adding Lists Together

In Python, lists can be added to each other using the plus symbol +. As shown in the code block, this will result in a new list containing the same items in the same order with the first list’s items coming first.

Note: This will not work for adding one item at a time (use .append() method). In order to add one item, create a new list with a single value and then use the plus symbol to add the list.

items = ['cake', 'cookie', 'bread'] total_items = items + ['biscuit', 'tart'] print(total_items) # Result: ['cake', 'cookie', 'bread', 'biscuit', 'tart']

Python Lists: Data Types

In Python, lists are a versatile data type that can contain multiple different data types within the same square brackets. The possible data types within a list include numbers, strings, other objects, and even other lists.

numbers = [1, 2, 3, 4, 10] names = ['Jenny', 'Sam', 'Alexis'] mixed = ['Jenny', 1, 2] list_of_lists = [['a', 1], ['b', 2]]

List Method .append()

In Python, you can add values to the end of a list using the .append() method. This will place the object passed in as a new element at the very end of the list. Printing the list afterwards will visually show the appended value. This .append() method is not to be confused with returning an entirely new list with the passed object.

orders = ['daisies', 'periwinkle'] orders.append('tulips') print(orders) # Result: ['daisies', 'periwinkle', 'tulips']

Aggregating Iterables Using zip()

In Python, data types that can be iterated (called iterables) can be used with the zip() function to aggregate data. The zip() function takes iterables, aggregates corresponding elements based on the iterables passed in, and returns an iterator. Each element of the returned iterator is a tuple of values.

As shown in the example, zip() is aggregating the data between the owners’ names and the dogs’ names to match the owner to their dogs. zip() returns an iterator containing the data based on what the user passes to the function. Empty iterables passed in will result in an empty iterator. To view the contents of the iterator returned from zip(), we can cast it as a list by using the list() function and printing the results.

owners_names = ['Jenny', 'Sam', 'Alexis'] dogs_names = ['Elphonse', 'Dr. Doggy DDS', 'Carter'] owners_dogs = zip(owners_names, dogs_names) print(list(owners_dogs)) # Result: [('Jenny', 'Elphonse'), ('Sam', 'Dr.Doggy DDS'), ('Alexis', 'Carter')]