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 listclear(): Removes all the elements from the listcopy(): Returns a copy of the listcount(): Returns the number of elements with the specified valueextend(): Add the elements of a list (or any iterable), to the end of the current listindex(): Returns the index of the first element with the specified valueinsert(): Adds an element at the specified positionpop(): Removes the element at the specified positionremove(): Removes the item with the specified valuereverse(): Reverses the order of the listsort(): 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)