Lists (interactive) - SOLVED#

List is an ordered sequence of information (data), which can be accessed by index (the position in the list).

  • A list is denoted by square brackets,
    \(\verb:[item1, item2,:\) \(\ldots\) \(\verb:, itemN]:\), and has elements separated by a comma.

  • An empty list is a similar object to an empty set in mathematics; An empty list is represented by \(\verb|[]|\).

  • Elements of the list are usually of the same type, e.g. integers, or floats, however it is possible to a list can contain mixed types.

  • List elements, unlike string elements, can be changed. This means that list is mutable.

When we want to store multiple objects in order, we need a list. There are several different ways to create a list. The simplest is with square brackets, e.g.

lst = [0, 1, 2, 3]

If we want to know the length of a list, we use one of Python’s built-in functions:

len(lst)

Try this, and also check the type of the list.

lst = [0, 1, 2, 3]

print(lst)
print(len(lst))
print(type(lst))
[0, 1, 2, 3]
4
<class 'list'>

Does a list have to contain only integers? Try putting other things in a list, like floats, strings, and other lists. Does the length count the lists inside a list?

lst_2 = [0,0.12,"banana",2,5,-0.354,2323]
print(len(lst_2))
7

Now make an empty list. What do you expect its length to be? Are you right?

lst_3 = []
print(len(lst_3))
0

Converting other types to lists#

Some things can be converted to lists. We do it the same way as converting to an integer or string, by using the name of the type:

list("a")

Try this, and try a longer string. Does it work with an integer or float? What if you call list on something that’s already a list?

b = [1232,434,2,3,1,21,3]
print(b)
c = list(b)
print(c)
[1232, 434, 2, 3, 1, 21, 3]
[1232, 434, 2, 3, 1, 21, 3]

Building a list with a for loop#

To build a list, we can start with an empty list, then in a loop append values to that list. Here’s how this would work:

my_list1 = []
for ii in range(10):
    my_list1.append(ii)
print(my_list1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]