Python Basics
Python Lists
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.
Create a List
Lists are created using square brackets:
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.
Access Items
You access the list items by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) # banana
Change List Items
To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) # ['apple', 'blackcurrant', 'cherry']
Add List Items
To add an item to the end of the list, use the append() method:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) # ['apple', 'banana', 'cherry', 'orange']
Remove List Items
There are several methods to remove items from a list:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist) # ['apple', 'cherry']