Python Lists

Python Lists

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 Dictionary, all with different qualities and usage.

Lists are created using square brackets [].

Create a List

thislist = ["apple", "banana", "cherry"]
print(thislist)

List Items

List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index [0], the second item has index [1] etc.

1. Access Items

You access the list items by referring to the index number.

Access Example

thislist = ["apple", "banana", "cherry"]
print(thislist[1]) # banana

2. Change Item Value

To change the value of a specific item, refer to the index number.

Change Value

thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Add and Remove Items

append() and insert()

To add an item to the end of the list, use the append() method. To insert a list item at a specified index, use the insert() method.

Add Items

thislist = ["apple", "banana"]
thislist.append("orange")
thislist.insert(1, "lemon")
print(thislist)

Removing Items

The remove() method removes the specified item. The pop() method removes the specified index (or the last item if index is not specified).


List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.

List Comprehension Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

// Create a new list containing only fruits with the letter "a" newlist = [x for x in fruits if "a" in x]

print(newlist) # ['apple', 'banana', 'mango']


Sorting Lists

Python lists have a built-in sort() method that will sort the list alphanumerically, ascending, by default.

Sort a List

cars = ["Ford", "BMW", "Volvo"]
cars.sort()
print(cars) # ['BMW', 'Ford', 'Volvo']

// Sort descending cars.sort(reverse=True) print(cars) # ['Volvo', 'Ford', 'BMW']


Exercise

?

Which method adds an element to the end of a list?