top of page

Lists

In this section, we'll talk about lists. These are structures in python that allow us to store data. If you've learned java before, lists are similar to arrays.

Lists

Lists are a single variable that are able to store multiple items. They are created using square brackets. The items we store do not have to be of the same data type. We can even store lists into other lists!

Examples

list1 = [1,2,3,4,5]

list2 = ["hello", 1, 10, "10", 10,]

list3 = ["string", list1, [1,2,3], 14]

In this example, we made 3 lists. The first list has only integer values, the second list has strings and integers, as well as repeat values. This is totally okay to do! Finally, the third list has a bit of everything. It contains a string, list1, the list [1,2,3], and an integer.

Methods

There are many useful methods that we can do with lists in Python. List Methods are actions that we can apply to lists that let us do useful things, such as add elements, sort, count number of elements, etc.

Example 1:

list1 = [1,2,3,4,5]

print(len(list1))

This will print the length of the list.

Example 2:

list1 = [1,2,3,4,5]

list 2 = [6,7,8,9,10]

list1.append(list2)

This will add list2 to the end of list1. In other words, list1 will be [1,2,3,4,5,[6,7,8,9,10]], once the program finishes.

Iteration

Iterating lists is when we loop through all of the elements in a list. This is useful when we want to consider a lot of data that is stored in these lists. 

Syntax: 

list = [item1, item2, item3]

for x in list:

    code

Example:

numbers = [1,3,4,6,12,3456]

sum = 0

for x in numbers:

    sum += x

print(sum)

In this example, we summed up all the numbers in the array, and printed the sum. We can also iterate using while loops.

Example:

list = ["grape", "banana", "strawberry"]

i = 0

while i < len(list):

    print(list[i])

    i = i + 1

In this example, we print all 3 words in the list. This is because we are iterating through the length of the list, and printing ecah element as we traverse.

Exercises:

1. Initialize an integer list of size 50. Now go through the positive numbers and add even numbers that are divisible by 7. Continue until the list reaches its size limit. Hint: make an upper bound for the number of iterations.

2. Write a Program to find the product of all elements in the list [2,4,6,7,8,9,123,1257,5423,0]

3. Make a string list. Find the sum of the lengths of all elements

4. Make an int list. Copy the elements to a new list but add 5 to each number.

bottom of page