Jump to content

Lists and Dictionaries: Difference between revisions

From Slow Like Wiki
Rob (talk | contribs)
No edit summary
Rob (talk | contribs)
No edit summary
Line 135: Line 135:
else:
else:
     print("No numbers!")
     print("No numbers!")
</syntaxhighlight>)
</syntaxhighlight>
Check a list against a list
Check a list against a list
<syntaxhighlight lang="python" line>
<syntaxhighlight lang="python" line>

Revision as of 14:46, 1 April 2024

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

Create a list of numbers and list statistics


numbers = list(range(1,11)) # list function makes a list, range function creates 1-10
odd_numbers = list(range(1, 11, 2)) #third parameter is step
even_numbers = list(range(2, 11, 2))

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

square_nos = [value ** 2 for value in range(1, 11)] # list comprehension
print(square_nos)
print(min(square_nos))
print(max(square_nos))
print(sum(square_nos))

Slice a list


print(square_nos[0:3]) # first three
print(square_nos[2:6]) # 3rd, 4th, 5th, 6th
print(square_nos[:5]) # first five
print(square_nos[5:]) # from 5th to end
print(square_nos[-3:]) # last three
print(square_nos[0:5:2]) # first five, step 2

for number in square_nos[::3]: # every 3rd number of entire list
    print(number)

Copy a list


new_squares = square_nos # new list is linked to old one
new_squares = square_nos[:] # creates a new, separate list

Tuples

Tuples are immutable lists. You cannot modify values in a tuple, but you can replace the entire tuple.


limits = (10, 20) # defines the tuple
limits = (10, 30) # redefines the tuple

If Statements

Conditional Tests


number = 1
number == 1 # returns True
number == 2 # returns False
number != 2 # returns True (because 1 is not equal to 2)
number < 2  # returns True
number > 2  # returns False

letter = A
number = 2 and letter = A # returns false as only one condition is true
number = 2 or letter = A # returns true as one condition is true

numbers =[1, 2, 3]
1 in numbers                  # returns true
1 in numbers and 4 in numbers # returns false
4 not in numbers              # returns true

If Statements


age = 18
if age >= 18:                               # use a colon like a for list
    print(f"At age {age}, you can drive.")
elif age = 17:                              # one or more optional
    print("Next year!")
else:                                       # optional
    print(f"{age} is too young!")

numbers = list(range(0,11))
print(numbers)

if numbers:                  # is there anything in numbers?
    for number in numbers:
        if number == 0:
            print(f"{number} is nothing at all!")
        elif number % 2:
            print(f"{number} is an even number.")
        else:
            print(f"{number} is an odd number.")
else:
    print("No numbers!")

Check a list against a list


library_books = ["Gravity's Rainbow", "Naked Lunch", 
    "Hopscotch", "Crash"]
orders = ["Gravity's Rainbow", "The Soft Machine", 
    "Hopscotch", "The Atrocity Exhibition"]

for order in orders:
    if order in library_books:
        print(f"{order} added to package.")
    else:
        print(f"Sorry, we don't have {order}.")