You are on page 1of 30

Lists

Lists

Great work getting this far! You’ll be a Python master in no time.

Let’s kick off module 5 by talking about lists

At their simplest, Lists are used to store items.

We can create a list by using square brackets with commas separating items. Like this:

words = ["Hello", "world", "!"]

PY
In that example the words list contains three string items: hello, world and !
If you want to access a certain item in the list, you can do this by using its index in square brackets. In our example, that would look like this:
For example:

words = ["Hello", "world", "!"]

print(words[0])

print(words[1])

print(words[2])

PY

Try it Yourself

The first list item's index is 0, rather than 1, as you might exp
Python Practice!
nums = [5, 4, 3, 2, 1]

print(nums[1])

ANS:
Lists

But lists aren’t just for shopping!

We can do some pretty cool stuff with them in Python. For example, we can use nested lists to represent 2D grids, such as matrices.
For example:

m=[

[1, 2, 3],

[4, 5, 6]

print(m[1][2])

PY
Try it Yourself

This is useful because a matrix-like structure can allow you to store data in row-column format, like in ticketing programs,
that need to store the seat numbers in a matrix, with their corresponding rows and numbers.

The code above outputs the 3rd item of the 2nd row.
Lists practice

Lists
Fill in the blanks to create a list and print its 3rd element.

list = _42, 55, 67]

print(list[-])
Strings

Strings can be indexed like lists too!

Indexing a string is like creating a list containing each character in the string.

For example:

str = "Hello world!"

print(str[6])

PY
Try it Yourself

Space (" ") is also a symbol and has an index.

Trying to access a non-existing index will result in an error.


Strings

What is the output of this code?

x = "Python"

print(x[1] + x[4])
List Operations

The list of cool things we can do with lists just keeps growing!
Lists can also be added and multiplied in the same way as strings.
For example:

nums = [1, 2, 3]

print(nums + [4, 5, 6])

print(nums * 3)

PY

Try it Yourself
Lists and strings share a lot of similarities - you can basically think of strings as lists of characters that can't be
changed.

The string "Hello" can be thought of as a list, where each character is an item in the list. The first item is "H",
the second item is "e", and so on.
last

List Operations
Figure out the output of this code:

x = [2, 4]

x += [6, 8]

print(x[2]//x[0])
Plus sign operator over lists means append items, so x = [2 , 4 , 6 , 8 ]
Then you access to third and first element (remember!! Iterables in python
are always 0-based index) to do a integer division "//" Don't be confused
with "/" that does the floor / floating point division 6 // 2 = 3
Whereas 6 / 2 = 3.0 Keep learning!!!
String Formatting

Strings have a format() function, which enables values to be embedded in it, using placeholders.

Example:

nums = [4, 5, 6]

msg = "Numbers: {0} {1} {2}". format(nums[0], nums[1], nums[2])

print(msg)

PY

Try it Yourself
Each argument of the format function is placed
in the string at the corresponding position,
which is determined using the curly braces { }.
String Formatting

What's the result of this code?

print("{0}{1}{0}".format("abra", "cad"))
String Formatting

You can also name the placeholders, instead of the index numbers.

Example:

a = "{x}, {y}".format(x=5, y=12)

print(a)

PY

Try it Yourself

Run the code and see how it works!


for Loop

There’s always more to say, but that was a pretty good intro to lists. Let’s move on and introduce a new loop.

The for loop is used to iterate over a given sequence, such as lists or strings.

The code below outputs each item in the list and adds an exclamation mark at the end:

words = ["hello", "world", "spam", "eggs"]

for word in words:

print(word + "!")

PY
Try it Yourself

In the code above, the word variable represents the corresponding item of the list in each iteration of the
loop.

During the 1st iteration, word is equal to "hello", and during the 2nd iteration it's equal to "world", and so on.
Fill in the blanks to create a valid loop:
letters = ['a', 'b', 'c']
for _ in letters_
print(_)
for Loops
for loop can be used to iterate over strings.

For example:

str = "testing for loops"

count = 0

for x in str:

if(x == 't'):

count += 1

print(count)

PY
Try it Yourself

The code above defines a count variable, iterates over the string and calculates the count of 't' letters in it. During each
iteration, the x variable represents the current letter of the string.

The count variable is incremented each time the letter 't' is found, so, at the end of the loop it represents the number of 't'
letters in the string.

Similar to while loops, the break and continue statements can be used in for loops, to stop the loop or jump to the
next iteration.
for Loops

What's the output of this code?

list = [2, 3, 4, 5, 6, 7]

for x in list:

if(x%2==1 and x>4):

print(x)

break
for vs while

So we’ve got the for and while loops, which can be used to execute a block of code multiple times. So which do we use and when?

Usually we’d use the for loop when the number of iterations is fixed. For example, iterating over a fixed list of items in a shopping
list.

The while loop is useful in cases when the number of iterations isn’t known and depends on some calculations and conditions in the
code block of the loop.

For example, ending the loop when the user enters a specific input in a calculator program.

While both, for and while loops can be used to achieve the same results, however, the for loop has cleaner and shorter syntax,
making it a better choice in most cases.
for vs while
Which construct can be used to iterate through a list?

Loops

Variable assignment

if statements
PROBLEM SET!
Problem
for Loops

You’re making a shopping cart program.

The shopping cart is declared as a list of prices, and you need to add functionality to apply a discount and
output the total price.

Take the discount percentage as input, calculate and output the total price for the shopping cart.

Use a for loop to iterate over the list.

Use the following formula to calculate the result of X% discount on $Y price: Y - (Y*X/100)
Code to start with!
cart = [15, 42, 120, 9, 5, 380]

discount = int(input())
total = 0

Problem set taken from:=

stackoverflow.com

You might also like