Jump to content

Lists and Dictionaries

From Slow Like Wiki
Revision as of 13:37, 31 March 2024 by Rob (talk | contribs)

Lists

Create a list


people = []                                # empty list
animals = ['daisy','pat','wabbit','bunny']

Access elements


print(animals[0])                        # first item
print(animals[-1])                       # last item
print(animals[-2])                       # penultimate item
print(f"{animals[0].title()} is a cow.") # in an f-string

Modify, add, insert elements


animals[3] = 'veau'      # replace item 3
animals.append('croc')   # add new item to end of list
animals.insert(1,'pato') # insert item at index 1

Remove elements


del animals[0]                 # delete item at index 0
popped_animal = animals.pop()  # remove last item
popped_animal = animals.pop(2) # remove item at index 2
animals.remove('veau')         # remove (first instance of) item by value

Organize Lists


animals.sort()             # sort values a-z
animals.sort(reverse=True) # sort values z-a
animals.reverse()          # reverse order (not z-a)
print(sorted(animals))     # temporarily sort
len(animals)               # returns number of items

Loop on a List


for animal in animals:                    # for loop requires a colon
    print(animal)                         # indent each line in the loop
    print(f"Hello {animal.title()}")
print(f"We have {len(animals)} animals!") # stop indenting after the loop