Skip to content

Learning Python: Day 9

Copying a list

  • copy a list by making a slice that includes the entire original list by omitting the first index and the second index ([:])

foods.py

my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]

friends_foods = my_foods [:]

print(“My favorite foods are:”)

print(my_foods)

print(“\nMy friend’s favorite foods are:”)

print(friend_foods)

My favorite foods are:

[‘pizza’, ‘falafel’, ‘carrot cake’]

My friend’s favorite foods are:

[‘pizza’, ‘falafel’, ‘carrot cake’]

  • to prove we have two separate lists, we’ll add a new food to each lsit

my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’]

friend_foods = my_foods[:]

my_foods.append(‘cannoli’)

friend_foods.append(‘ice cream’)

print(“My favorite foods are:”)

print(my_foods)

print(“\nMy friend’s favorite foods are:”)

print(friend_foods)

My favorite foods are:

[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]

My friend’s favorite foods are:

[‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]

Tuples

  • immutable – value that cannot change
  • tuple – immutable list

Defining a tuple

  • looks like a list, except you use parentheses instead of square brackets
  • can access individual elements by using each item’s index
  • for example, use a tuple for the dimensions of a rectangle that should always be the same size

dimensions.py

dimensions = (200, 50)

print(dimensions[0])

print(dimensions[1])

200

50

  • trying to alter a tuple will return an error
  • can define a tuple with one element by using a comma

my_t = (3,)

Looping through all values in a tuple

dimensions = (200, 50)

for dimension in dimensions:

print(dimension)

200

50

Writing over a tuple

  • can’t modify a tuple, but you can assign a new value to a variable that represents a tuple
  • for example, if we wanted to change the dimensions of this rectangle, we could redefine the entire tuple

dimensions = (200, 50)

print(“Original dimensions:”)

for dimension in dimensions:

print(dimension)

dimensions = (400, 100)

print(“\nModified dimensions:”)

for dimension in dimensions:

print(dimension)

Original dimensions:

200

50

Modified dimensions:

400

100

  • tuples are simple data structures that should be used to store a set of values that should not change throughout the life of the problem
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *