2 min read

Python Lists

Lists are used to store multiple items in a single variable. A list is a collection which is ordered and changeable. Allows duplicate members.

Creating a List

Lists are created using square brackets:

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

Access Items

List items are indexed, the first item has index [0], the second item has index [1] etc.

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

Change Item Value

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

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

List Comprehension

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

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)

See programming/python/list-comprehensions for more details.

List Methods

Python has a set of built-in methods that you can use on lists.

  • append(): Adds an element at the end of the list
  • clear(): Removes all the elements from the list
  • copy(): Returns a copy of the list
  • count(): Returns the number of elements with the specified value
  • extend(): Add the elements of a list (or any iterable), to the end of the current list
  • index(): Returns the index of the first element with the specified value
  • insert(): Adds an element at the specified position
  • pop(): Removes the element at the specified position
  • remove(): Removes the item with the specified value
  • reverse(): Reverses the order of the list
  • sort(): Sorts the list

Loop Through a List

You can loop through the list items by using a for loop:

thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)

programming/python/python