ARTIFICIAL INTELLIGENCE
PROGRAMMING
LESSON 4: LIST PROCESSING IN PYTHON
Booleans
• 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
• This is because Python implements its Boolean values as a
subclass of int, as you saw before.
Strings
• Strings are pieces of text or sequences of characters that you
can define using single, double, or triple quotes:
• >>>
• >>> # Use single quotes
• >>> greeting = 'Hello there!'
• >>> greeting
• 'Hello there!'
•
• >>> # Use double quotes
• >>> welcome = "Welcome to Real Python!"
• >>> welcome
• 'Welcome to Real Python!'
•
• >>> # Use triple quotes
• >>> message = """Thanks for joining us!"""
• >>> message
• 'Thanks for joining us!'
•
• >>> # Escape characters
• >>> escaped = 'can\'t'
• >>> escaped
• "can't"
• >>> not_escaped = "can't"
• >>> not_escaped
• "can't"
• Note that you can use different types of quotes to create string
objects in Python. You can also use the backslash character (\)
to escape characters with special meaning, such as the quotes
themselves.
• Once you define your string objects, you can use the plus operator
(+) to concatenate them in a new string:
• >>>
• >>> "Happy" + " " + "pythoning!"
• 'Happy pythoning!'
• When used on strings, the plus operator (+) concatenates them
into a single string. Note that you need to include a blank space ("
") between words to have proper spacing in your resulting string. If
you need to concatenate a lot of strings, then you should consider
using .join(), which is more efficient.
• Python comes with many useful built-in functions and
methods for string manipulation. For example, if you pass a
string as an argument to len(), then you’ll get the
string’s length, or the number of characters it contains:
• >>>
• >>> len("Happy pythoning!")
• 16
• When you call len() using a string as an argument, you get
the number of characters, including any blank spaces, in the
input string.
• The string class (str) provides a rich set of methods that are
useful for manipulating and processing strings. For
example, str.join() takes an iterable of strings and joins them
together in a new string. The string on which you call the
method plays the role of a separator:
• >>>
• >>> " ".join(["Happy", "pythoning!"])
• 'Happy pythoning!'
• str.upper() returns a copy of the underlying string with all the
letters converted to uppercase:
• >>>
• >>> "Happy pythoning!".upper()
• 'HAPPY PYTHONING!'
• str.lower() returns a copy of the underlying string with all the
letters converted to lowercase:
• >>>
• >>> "HAPPY PYTHONING!".lower()
• 'happy pythoning!'
• str.format() performs a string formatting operation. This method
provides a lot of flexibility for string formatting and interpolation:
• >>>
• >>> name = "John Doe"
• >>> age = 25
• >>> "My name is {0} and I'm {1} years old".format(name, age)
• "My name is John Doe and I'm 25 years old"
• You can also use an f-string to format your strings without
using .format():
• >>>
• >>> name = "John Doe"
• >>> age = 25
• >>> f"My name is {name} and I'm {age} years old"
• "My name is John Doe and I'm 25 years old"
• Python’s f-strings are an improved string formatting syntax.
They’re string literals with an f at the beginning, outside the
quotes. Expressions that appear in embedded curly braces
({}) are replaced with their values in the formatted string.
• Strings are sequences of characters. This means that you can retrieve
individual characters from a string using their positional index. An index is
a zero-based integer number associated with a specific position in a
sequence:
• >>>
• >>> welcome = "Welcome to Real Python!"
• >>> welcome[0]
• 'W'
• >>> welcome[11]
• 'R'
• >>> welcome[-1]
• '!'
• An indexing operation retrieves the character at the position indicated by
the given index. Note that a negative index retrieves the element in reverse
order, with -1 being the index of the last character in the string.
• You can also retrieve a part of a string by slicing it:
• >>>
• >>> welcome = "Welcome to Real Python!"
• >>> welcome[0:7]
• 'Welcome'
• >>> welcome[11:22]
• 'Real Python'
• Slicing operations take the element in the form [start:end:step].
Here, start is the index of the first item to include in the slice,
and end is the index of the last item, which isn’t included in the
returned slice. Finally, step is an optional integer representing the
number of items to jump over while extracting the items from the
original string. A step of 2, for example, will return every other
element between start and stop.
Lists
• Lists are usually called arrays in nearly every other programming
language. In Python, lists are mutable sequences that group various objects
together. To create a list, you use an assignment with a sequence of
comma-separated objects in square brackets ([]) on its right side:
• >>>
• >>> # Define an empty list
• >>> empty = []
• >>> empty
• []
•
• >>> # Define a list of numbers
• >>> numbers = [1, 2, 3, 100]
• >>> numbers
• [1, 2, 3, 100]
• Lists can contain objects of different data types, including other lists. They can
also be empty. Since lists are mutable sequences, you can modify them in place
using index notation and an assignment operation.
• >>> # Modify the list in place
• >>> numbers[3] = 200
• >>> numbers
• [1, 2, 3, 200]
•
• >>> # Define a list of strings
• >>> superheroes = ["batman", "superman", "spiderman"]
• >>> superheroes
• ['batman', 'superman', 'spiderman']
•
• >>> # Define a list of objects with different data types
• >>> mixed_types = ["Hello World", [4, 5, 6], False]
• >>> mixed_types
• ['Hello World', [4, 5, 6], False]
• Since lists are sequences just like strings, you can access their individual items
using zero-based integer indices:
• >>>
• >>> numbers = [1, 2, 3, 200]
• >>> numbers[0]
• 1
• >>> numbers[1]
• 2
•
• >>> superheroes = ["batman", "superman", "spiderman"]
• >>> superheroes[-1]
• "spiderman"
• >>> superheroes[-2]
• "superman"
• 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']
• list.sort() sorts the underlying list in place:
• >>>
• >>> fruits.sort()
• >>> fruits
• ['apples', 'blueberries', 'grapes', 'oranges']
• list.pop() takes an integer index as an argument, then
removes and returns the item at that index in the underlying
list:
• >>>
• >>> numbers_list = [1, 2, 3, 200]
• >>> numbers_list.pop(2)
• 3
• >>> numbers_list
• [1, 2, 200]
• Lists are quite common and versatile data structures in
Python. They’re so popular that developers sometimes tend
to overuse them, which can make the code inefficient.