Skip to content

Chapter 4

Jarlin Almanzar edited this page Oct 26, 2019 · 3 revisions

Working with lists

Iterating through a list

magicians = ['alice', 'david', 'Carolina']
for magician in magicians:
    print(magician)

Numerical Lists

for value in range(1, 5):
    # inclusive will not include the last value in a range
    print(value)

Even Lists

#Starts at 2 and increments by 2 until it reaches or passes the final numbers that being 11
for value in range(2, 11, 2):
    print(value)

Square Lists

squares = []
for value in range(1, 11):
    square = value**2
    squares.append(square)

print(squares)

Statistics Lists

digits = [1,2,3,4,5,6,7,8,9,10]
print(min(digits))
print(max(digits))
print(sum(digits))

List Comprehension

List comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element.

Squares comprehension

squares = [value**2 for value in range(1, 12)]
print(squares)

Slicing A list

# [0:3] would return the elements from the indices 0 to 2
# [:3] Can also be omitted
# [0:] Given start value to end
players = ['adam', 'atom', 'atem', 'ahtam']
print(players[0:3])

Slicing and Looping

players = ['adam', 'atom', 'atem', 'ahtam']
for player in players[:-1]:
    print(player)
print("")

for player in players[:3]:
    print(player)
print("")

for player in players[::-1]:
    print(player)

Copying a list

my_foods = ['Pizza', 'falafel', 'carrot cake']
friends_food = my_foods[:] 
print(my_foods)
print(friends_food)

Tuples

A list of items that cannot be changed, as they are immutable, and an immutable list is called a tuple Defining a Tuple: It looks like a list instead we use parenthesis

dimension = (200,300)
print(dimension[0])
print(dimension[1])

Iterating through a tuple

dimensions = (200,300)
for dimension in dimensions:
    print(dimension)

Writing Over a tuple

dimensions = (300,400)
for dimension in dimensions:
    print(dimension)

Styling Your Code

Indentation

It's recommend to have four spaces or a tab per indentation level DO NOT MIX SPACES AND TABS

Line Length

Each line should be less than 80 characters, some prefer 99 characters Comments should at most 72 character per line

Blank Lines

To group parts of your program visually, use blank lines

Clone this wiki locally