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 [].
thislist = ["apple", "banana", "cherry"] print(thislist)
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.
You access the list items by referring to the index number.
thislist = ["apple", "banana", "cherry"] print(thislist[1]) # banana
To change the value of a specific item, refer to the index number.
thislist = ["apple", "banana", "cherry"] thislist[1] = "blackcurrant" print(thislist)
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.
thislist = ["apple", "banana"]
thislist.append("orange")
thislist.insert(1, "lemon")
print(thislist)
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 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"]// 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']
Python lists have a built-in sort() method that will sort the list alphanumerically, ascending, by default.
cars = ["Ford", "BMW", "Volvo"] cars.sort() print(cars) # ['BMW', 'Ford', 'Volvo']// Sort descending cars.sort(reverse=True) print(cars) # ['Volvo', 'Ford', 'BMW']
Which method adds an element to the end of a list?