Python Day 3: Lists & Branching

[Pages:29]Python Day 3: Lists & Branching

IWKS 2300 Fall 2019 John K. Bennett

Lists Basics

A list is a built-in data structure for storing and accessing objects that belong in a specific sequence.

Two ways to create an empty list in python:

list_one = list()

list_two = []

Lists Basics (Continued ...)

A list can contain all sorts of objects, including: integers, strings, booleans, floats, and even other lists.

Python allows you to have multiple data types in the same list.

example = [112, "Apple", True, 1.75, [57, False]]

More on Lists

Add element to the list:

list_two.append(7)

List can be concatenated:

numbers = [1, 2, 3] letters = ['a', 'b', 'c'] print(numbers + letters)

[1, 2, 3, 'a', 'b', 'c']

4

More on Lists (Continued ...)

What gets printed when we change the order?

print(letters + numbers) ['a', 'b', 'c', 1, 2, 3]

Order is important!

What about now?

letters.append('d') print(letters + numbers)

['a', 'b', 'c', 'd', 1, 2, 3]

Console Output

List Indexing

Lists in python are indexed from 0.

3 45

0

1

2 -3 -2 -1

my_list = ['a', 'b', 'c', 1, 2, 3]

Python also wraps around to the end of the list. The last item is index -1.

>>> my_list[5] 3

>>> my_list[-1] 3

Note: You can only wrap around once.

my_list[-7] will cause an error!

Another Kind of Equals

We're used to the = operator for assignments. In Python, the == operator is for equality testing.

An expression a == b will be True iff a has the same value as b, False otherwise.

>>> year = 2019 >>> year == 2018 False >>> year == 2019 True

>>> month = "January" >>> month == "january" False >>> month == "January" True

Comparisons Operators

== Equals to != Not Equals to < Less than > Greater than = Greater than or

Equals to

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download