Lists of strings, floats and more
So far most of your lists have held whole numbers. A list can hold values of any type: strings, floating point numbers, Booleans, even other lists (step 3 of this module shows those). Everything you know about lists works the same way, whatever is inside.
A list of strings
guests = ["Maya", "Leo", "Iris"]
guests.append("Omar")
print(guests)
print("Guests:", len(guests))
guests.sort()
for guest in guests:
print(guest)
['Maya', 'Leo', 'Iris', 'Omar']
Guests: 4
Iris
Leo
Maya
OmarWhen Python prints a whole list, it shows each string in quotes, so you can see where one ends and the next begins. sort puts strings in alphabetical order.
Careful with capital letters: Python compares strings character by character, and every capital letter comes before every small letter. So "Zoe" comes before "adam":
>>> sorted(["adam", "Zoe", "bea"])
['Zoe', 'adam', 'bea']A list of floats
A list of floating point numbers works with sum, min and max just like a list of integers:
rainfall = [12.5, 0.0, 3.2, 8.8, 0.4]
print("Wettest day:", max(rainfall))
mean = sum(rainfall) / len(rainfall)
print(f"Mean: {mean:.2f} mm")
Wettest day: 12.5
Mean: 4.98 mmMixing types
One list can even hold values of different types, such as a product's name, the number in stock and the price: ["lamp", 3, 19.99]. That's allowed, but some things stop working. To sort a list, Python compares its items with each other, and it can't say whether a number is smaller than a string:
mixed = [3, "lamp", 19.99]
mixed.sort()
Traceback (most recent call last):
File "main.py", line 2, in <module>
mixed.sort()
~~~~~~~~~~^^
TypeError: '<' not supported between instances of 'str' and 'int'The < in the message is the comparison that sort tried. Most lists hold one type of value, and step 3 shows when a mixed list makes sense.