Lesson 4 Strings and List Processing in Python
Lesson 4 Strings and List Processing in Python
PROGRAMMING
• Booleans are implemented as a subclass of integers with only two possible values in
Python: True or False. Note that these values must start with a capital letter.
• You use Boolean values to express the truth value of an expression or object. Booleans are handy
when you’re writing predicate functions or when you’re using comparison operators, such as greater
than (>), lower than (<), equal (==), and so on:
• >>>
• >>> 2 < 5
• True
• >>> 4 > 10
• False
• >>> 4 <= 3
• False
• >>> 3 >= 3
• True
• >>> 5 == 6
• False
• >>> 6 != 9
• True
• Python provides a built-in function, bool(), that is closely related to Boolean values. Here’s how
it works:
• >>>
• >>> bool(0)
• False
• >>> bool(1)
• True
•
• >>> bool("")
• False
• >>> bool("a")
• True
•
• >>> bool([])
• False
• >>> bool([1, 2, 3])
• True
• bool() takes an object as an argument and returns True or False according to the object’s truth
value. To evaluate the truth value of an object, the function uses Python’s truth testing rules.
• On the other hand, int() takes a Boolean value and
returns 0 for False and 1 for True:
• >>>
• >>> int(False)
• 0
• >>> int(True)
• 1
• Indexing operations also work with Python lists, so you can retrieve any item in a list
by using its positional index. Negative indices retrieve items in reverse order,
starting from the last item.
• You can also create new lists from an existing list using a slicing operation:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> new_list = numbers[0:3]
• >>> new_list
• [1, 2, 3]
• If you nest a list, a string, or any other sequence within another list, then you
can access the inner items using multiple indices:
• >>>
• >>> mixed_types = ["Hello World", [4, 5, 6], False]
• >>> mixed_types[1][2]
• 6
• >>> mixed_types[0][6]
• 'W'
• In this case, the first index gets the item from the container list, and the second
index retrieves an item from the inner sequence.
• You can also concatenate your lists using the plus operator:
• >>>
• >>> fruits = ["apples", "grapes", "oranges"]
• >>> veggies = ["corn", "kale", "mushrooms"]
• >>> grocery_list = fruits + veggies
• >>> grocery_list
• ['apples', 'grapes', 'oranges', 'corn', 'kale', 'mushrooms']
• Since lists are sequences of objects, you can use the same
functions you use on any other sequence, such as strings.
• Given a list as an argument, len() returns the list’s length, or
the number of objects it contains:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> len(numbers)
• 4
• Below is a summary of some of the most commonly used methods.
• list.append() takes an object as an argument and adds it to the end
of the underlying list:
• >>>
• >>> fruits = ["apples", "grapes", "oranges"]
• >>> fruits.append("blueberries")
• >>> fruits
• ['apples', 'grapes', 'oranges', 'blueberries']