You need to know three types of creating collections of data:
A tuple
a_tuple = (54, 99, 3.142)
A list
a_list = ['red', 'green', 'blue']
A dictionary
a_dictionary = {
foreground: 'red',
background: 'green',
text: 'blue',
}
Output: >> 1
fruit_tuple = (
'apple',
'banana',
'strawberry',
'orange',
)
print(fruit_tuple.index('banana'))
Remember tuples/lists start at zero
Display the position of an item in a list/tuple:
Output: >> strawberry
fruit_tuple = (
'apple',
'banana',
'strawberry',
'orange',
)
print(fruit_tuple[2])
Display a item from a tuple/list:
>> ['Albert','Bart','Charles','David','Edward']
>> Albert Bart Charles David Edward
names_list = [
'Albert',
'Bart',
'Charles',
'David',
'Edward',
]
print(names_list)
print(*names_list)
Create a list (plus extra!):
>> Albert Bart Charles David Edward
>> Albert Bart David Edward
names_list = [
'Albert',
'Bart',
'Charles',
'David',
'Edward',
]
print(*names_list)
del names_list[2]
print(*names_list)
Delete an item from a list:
>> Albert Bart Charles David Edward
>> Albert Bart Charles David Edward Frank
names_list = [
'Albert',
'Bart',
'Charles',
'David',
'Edward',
]
print(*names_list)
names_list.append('Frank')
print(*names_list)
Add an item to the end of a list:
>> Edward Albert Charles David Bart
>> Albert Bart Charles David Edward
>> Edward Albert Charles David Bart
names_list = [
'Edward',
'Albert',
'Charles',
'David',
'Bart',
]
print(*names_list)
print(sorted(names_list))
print(*names_list)
Display a sorted tuple/list:
>> Edward Albert Charles David Bart
>> Albert Bart Charles David Edward
names_list = [
'Edward',
'Albert',
'Charles',
'David',
'Bart',
]
print(*names_list)
names_list.sort()
print(*names_list)
Sort a list:
You cannot sort a tuple. Tuples cannot be changed by the program.
>> {1: 'red', 2: 'green', 3: 'blue'}
colours = {
1:'red',
2:'green',
3:'blue',
}
print(colours)
Create and display a dictionary:
>> {1: 'red', 2: 'green', 3: 'blue'}
>> {1: 'red', 2: 'purple', 3: 'blue'}
colours = {
1:'red',
2:'green',
3:'blue',
}
print(colours)
colours[2] = 'purple'
print(colours)
Change a value in a dictionary: