Python Essential Classroom Series – 15/Sept/2021

Lists continued

  • Refer Here for the some more list examples with list comprehensions

Tuples vs Lists

  • You can often use tuples in the place of lists, but they have many fewer functions.
  • Why not just use the lists instead of tuples everywhere
    • Tuples use less space
    • You can use tuples are dictionary keys
    • Named Tuples can be a simple alternatives to objects

Note: Mutable types (lists, dictionaries and sets) have comprehensions. Immutable types like strings and tuples need to be created with other methods

Exercise

  • Write a python program to store first 100 prime numbers in a list
max_prime = 100
number = 2
prime_numbers = []

while len(prime_numbers) < max_prime:
    index = 2 
    for index in range(2, number//2 + 1):
        if number%index == 0:
            break
    else:
        prime_numbers.append(number)
    number = number + 1

print(f"First {max_prime} prime numbers are {prime_numbers}")

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin