From my notes:
List
A list is simply a sequence of values stored in a specific order with each value identified by its position in that order.
A list must be finite. List items are separated by commas and surrounded by square brackets.
Number List
even_numbers = [2,4,6,8,10]
Word List
words = ['the','cat','sat','on','the','mat']
String List
>>> list (‘Hello!’)
['H', 'e', 'l', 'l', 'o', '!']
Lists are …
-
ordered
- the items have a defined order, and that order will not change.
-
indexed
- the first item has index [0], the second item has index [1] etc.
-
changeable
- meaning that we can change, add, and remove items in a list after it has been created.
If you add new items to a list, the new items will be placed at the end of the list.
Since lists are indexed, lists can have items with duplicate values.
List items can be of any data type:
Example
#String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
# A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male", False]
You can change an item in a list by referencing its index number.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = numbers[4]
print(n)
numbers[4] = 40
n = numbers[4]
print(n)
.append()
used to add an item to the end of a list.
To remove or delete a list item, there are two ways to do this:
del list_name[index_number]
or list_name.remove(index_number)
Tuple
Tuples are created with round brackets, and the items are ordered, unchangeable and allow duplicate values.
Example
# Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuples are …
-
ordered
- the items have a defined order, and that order will not change.
-
indexed
- the first item has index [0], the second item has index [1] etc.
-
unchangeable
- meaning that we cannot change, add, or remove items in a Tuple after it has been created.
Since tuples are indexed, tuples can have items with duplicate values of strings, integers and boolean values
Example
# String, int and boolean data types:
tuple2 = ("cherry", "apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3, 1, 0, 9)
tuple3 = (True, False, False)