There are four collection data types in the Python programming language:
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.
More information about data structures (arrays) can be found here: https://docs.python.org/3/tutorial/datastructures.html
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
# Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Output:
['apple', 'banana', 'cherry']
You access the list items by referring to the index number:
# Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output:
banana
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
# Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output:
cherry
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.
# Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Output:
['cherry', 'orange', 'kiwi']
Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
# This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
Output:
['apple', 'banana', 'cherry', 'orange']
By leaving out the end value, the range will go on to the end of the list:
# This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Output:
['cherry', 'orange', 'kiwi', 'melon', 'mango']
Specify negative indexes if you want to start the search from the end of the list:
# This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output:
['orange', 'kiwi', 'melon']
To change the value of a specific item, refer to the index number:
# Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Output:
['apple', 'blackcurrant', 'cherry']
You can loop through the list items by using a for loop:
# Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Output:
apple
banana
cherry
To determine if a specified item is present in a list use the in keyword:
# Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output:
Yes, 'apple' is in the fruits list
To determine how many items a list has, use the len() function:
# Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:
3
To add an item to the end of the list, use the append() method:
# Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:
['apple', 'banana', 'cherry', 'orange']
To add an item at the specified index, use the insert() method:
# Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output:
['apple', 'orange', 'banana', 'cherry']
There are several methods to remove items from a list:
# The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output:
['apple', 'cherry']
# The pop() method removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Output:
['apple', 'banana']
# The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Output:
['banana', 'cherry']
# The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist
# The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output:
[]
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.
There are ways to make a copy, one way is to use the built-in List method copy().
# Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:
['apple', 'banana', 'cherry']
Another way to make a copy is to use the built-in method list().
# Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output:
['apple', 'banana', 'cherry']
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
# Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output:
['a', 'b', 'c', 1, 2, 3]
Another way to join two lists are by appending all the items from list2 into list1, one by one:
# Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output:
['a', 'b', 'c', 1, 2, 3]
Or you can use the extend() method, which purpose is to add elements from one list to another list:
# Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output:
['a', 'b', 'c', 1, 2, 3]
It is also possible to use the list() constructor to make a new list.
# Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)
Output:
['apple', 'banana', 'cherry']
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
# Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Output:
('apple', 'banana', 'cherry')
Item access and indexing works the same as a list, but you cannot add or remove items from a tuple.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.
# Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
Output:
('apple', 'kiwi', 'cherry')
To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.
# One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Output:
<class 'tuple'>
<class 'str'>
To join two or more tuples you can use the + operator:
# Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Output:
('a', 'b', 'c', 1, 2, 3)
tuple()
ConstructorIt is also possible to use the tuple() constructor to make a tuple.
# Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Output:
('apple', 'banana', 'cherry')
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
# Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Output:
{'apple', 'banana', 'cherry'}
Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Since sets are unordered and items have no index, you cannot access them directly. However, you can loop through a set:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
banana
apple
cherry
Note: The contents are printed in random order.
Items can be added using the add()
method:
thisset.add("orange")
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.
# Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
You can access the items of a dictionary by referring to its key name, inside square brackets:
# Get the value of the "model" key:
x = thisdict["model"]
There is also a method called get()
that will give you the same result:
# Get the value of the "model" key:
x = thisdict.get("model")
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
thisdict ={
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Output:
{'brand': 'Ford', 'year': 1964}