View on GitHub

Python-Tutorial

https://github.com/kdheepak/Python-Tutorial

Lists and Dictionaries

Lists

list_of_numbers = [1, 2, 3]
list_of_numbers[0]
list_of_numbers[1]
list_of_numbers[2]
list_of_numbers[3]
list_of_numbers[-1]
list_of_numbers[-4]
list_of_numbers[0:2]
0:2
(0:2)
list_of_numbers[0:10]
list_of_numbers[0:100]
list_of_numbers[0:]
list_of_numbers[:]
list_of_numbers[-100:100]
list_of_numbers[0:3:1]
list_of_numbers[0:3:2]
list_of_numbers[::-1]
list_of_numbers + list_of_numbers
list_of_numbers * 5
len(list_of_numbers)
list_of_characters = "hello world"
len(list_of_characters)
list_of_characters[0]
list_of_characters[0:5]
list_of_characters[5:]
list_of_characters[:5] + list_of_characters[5:]
for i in list_of_numbers:
    print(i)
for c in list_of_characters:
    print(c)
if 1 in list_of_numbers:
    print("1 is in the list_of_numbers")
if "hello" in list_of_characters:
    print("hello is part of the string")

Methods

list_of_numbers = [1, 2, 3]
list_of_numbers.append(5)
list_of_numbers
list_of_numbers.insert(3, 4)
list_of_numbers
list_of_numbers.insert(0, 0)
list_of_numbers
list_of_numbers[::-1]
list_of_numbers.sort()
list_of_numbers
names = [
    "JOHN",
    "JANE",
]
for n in names:
    print(n)
for n in names:
    print(n.lower())
for n in names:
    n.lower()
    print(n)
for n in names:
    t = n.lower()
    print(n, t)
def append(list_of_strings):
    list_of_strings.append("World")
l = ["hello"]
append(l)
l

def append(string):
    string = string + "World"
s = "hello"
append(s)
s

Exercise

list_of_numbers = list(range(0, 100))

Dictionaries

myhouse1 = {"type": "apartment", "color": "white", "square_feet": 2000}
myhouse1
myhouse1["color"]
myhouse2 = {'color': 'white', 'square_feet': 2000.0, 'type': 'apartment'}
myhouse2
myhouse1 == myhouse2
animals = []

while True:
    animal = {}
    name = input("Enter the name of a animal: ")
    color = input(f"Enter the color of the animal {name}: ")

    animal["name"] = name
    animal["color"] = color

    animals.append(animal)

    if len(animals) >= 3:
        break

animals

Exercise

SPACES = 10
spaces = (SPACES - len("Name"))
header = f"Name {' ' * spaces} | Color"
print(header)
print(len(header) * "-")
for animal in animals:
    spaces = SPACES - len(animal["name"])
    print(f"{animal['name']} {' ' * spaces} | {animal['color']}")

See string formatting in Python