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:
Example:
mylist = ["apple", "banana", "grapes"]
print(mylist)
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.
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the list.
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Since lists are indexed, lists can have items with the same value:
Example:
mylist = ["apple", "banana", "grapes", "apple", "grapes"]
print(mylist)
To determine how many items a list has, use the len() function:
Example:
print the number of items in the list
mylist = ["apple", "banana", "cherry","grapes"]
print(len(mylist))
List items can be of any data type:
Example:
string, int and boolean data types
list1 = ["apple", "banana", "cherry","grapes"]
list2 = [1, 5, 7, 9, 3,11]
list3 = [True, False, False]
From Python's perspective, lists are defined as objects with the data type 'list':
Example:
mylist = ["apple", "banana", "cherry","grapes"]
print(type(mylist))
It is also possible to use the list() constructor when creating a new list.
Example:
Using the list() constructor to make a List:
mylist = list(("apple", "banana", "cherry"))
# note the double round-brackets
print(mylist)
There are four collection data types in the Python programming language:
List items are indexed and you can access them by referring to the index number:
Example:
Print the third item of the list:
mylist = ["apple", "banana", "cherry","grapes"]
print(mylist[2])
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example:
Print the last item of the list
mylist = ["apple", "banana", "cherry","grapes"]
print(mylist[-1])
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example:
mylist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango","grapes"]
print(mylist[2:5])
To determine if a specified item is present in a list use the in keyword:
Example:
mylist=["apple", "banana", "cherry","grapes"]
if "apple" in mylist:
print("Yes, 'apple is in the fruit list")
To change the value of a specific item, refer to the index number:
Example:
mylist = ["apple", "banana", "cherry","grapes"]
mylist[1] = "orange"
print(mylist)
To change the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values:
Example:
mylist = ["apple", "banana", "cherry", "orange", "kiwi", "mango","grapes"]
mylist[1:3] = ["orange", "watermelon"]
print(mylist)
To add an item to the end of the list, use the append() method:
Examples:
Using the append() method to append an item:
mylist = ["apple", "banana", "cherry","orange"]
mylist.append("grapes")
print(mylist)
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example:
mylist = ["apple", "banana", "cherry","grapes"]
mylist.insert(1, "orange")
print(mylist)
To append elements from another list to the current list, use the extend() method.
Example:
add the elements of mylist to mylist1
list1 = ["apple", "banana", "cherry"]
list2 = ["mango", "pineapple", "papaya"]
list1.extend(list2)
print(list1)
Remove specified item
The remove() method removes the specified item.
Example:
mylist = ["apple", "banana", "cherry","orange"]
mylist.remove("banana")
print(mylist)
The pop() method removes the specified index.
Example:
mylist = ["apple", "banana", "cherry","orange"]
mylist.pop(1)
print(mylist)
The clear() method empties the list.
The list still remains, but it has no content.
Example:
mylist = ["apple", "banana", "cherry","grapes"]
mylist.clear()
print(mylist)
You can loop through the list items by using a for loop:
Example:
print all items in the list one by one.
mylist = ["apple", "banana", "cherry","orange"]
for x in mylist:
print(x)
You can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
Example:
mylist = ["apple", "banana", "cherry","grapes"]
for i in range(len(mylist)):
print(mylist[i])
You can loop through the list items by using a while loop.
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes.
Remember to increase the index by 1 after each iteration.
Example
Print all items, using a while loop to go through all the index numbers
mylist = ["apple", "banana", "cherry","orange"]
i = 0
while i < len(mylist):
print(mylist[i])
i = i + 1
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
Example:
mylist = ["orange", "mango", "kiwi", "pineapple", "banana","grapes"]
mylist.sort()
print(mylist)
To sort descending, use the keyword argument reverse = True:
Example:
mylist = ["orange", "mango", "kiwi", "pineapple", "banana","grapes"]
mylist.sort(reverse = True)
print(mylist)
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and changes made in list1 will automatically also be made in list2.
mylist = ["apple", "banana", "cherry","grapes"]
mylist = mylist.copy()
print(mylist)
mylist = ["apple", "banana", "cherry"]
mylist1 = list(mylist1)
print(mylist1)
You can also make a copy of a list by using the : (slice) operator.
Example:
mylist = ["apple", "banana", "cherry"]
mylist1 = mylist[:]
print(mylist1)
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Python has a set of built-in methods that you can use on lists.
Method | Descriptions |
---|---|
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 |