Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered and unindexed. No duplicate members.
- Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Run example »
The list() Constructor
It is also possible to use the list() constructor to make a list. To add an item to the list use append() object method. To remove a specific item use the remove() object method. The len() function returns the length of the list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Run example »
Example
Using the append() method to append an item:
thislist = list(("apple", "banana", "cherry"))
thislist.append("damson")
print(thislist)
Run example »
Example
Using the remove() method to remove an item:
thislist = list(("apple", "banana", "cherry"))
thislist.remove("banana")
print(thislist)
Run example »
Example
The len() method returns the number of items in a list:
thislist = list(("apple", "banana", "cherry"))
print(len(thislist))
Run example »
List Methods
Python has a set of built-in methods that you can use on lists.
Method | Description |
---|---|
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 first item with the specified value |
reverse() | Reverses the order of the list |
sort() | Sorts the list |