Python Classroom Series – 04/Mar/2020

mutable objects

  • Changing the value with out allocating a new memory (changing will be allowed)

Lists

  • simple collection of objects
  • list can have items of different data types
  • basic syntax
items = [1,2,3,4]

new_items = list(items)

different_items = [1,'hi', 2.0, True]
  • Copying lists

    • Shallow copy : a new memory location will be created, so changes in source will not impact the new list
    items = [1,2,3]
    new_items = items.copy()
    other_items = list(items)
    
    • deep copy: points to same memory location, changes to source will impact the new variable used for list
    items = [1,2,3]
    new_items = items
    
  • Iterating lists is very simple with for

items = [1,2,3]
for item in items:
    print item

# output
1
2
3
  • Exercise:

    • Try combining two list into one
    • adding and removing items from list
  • Sample program to collect input and add items to list and multiply the list by 2

items = []
while True:
    input_item = int(input('Enter item to be added to list. Enter -1 to exit '))
    if input_item == -1:
        break
    items.append(input_item)
print(f'The items you entered are {items}')
new_list = []
for item in items:
    #print(item*2)
    new_list.append(item*2)
print(f'multiplied list by 2 with new result = {new_list}')
  • Write a program to find the smallest and largest item in list
items = [1,2,4543,0,-1]
### Output ######
min of [1,2,4543,0,-1] is -1
max of [1,2,4543,0,-1] is 4543

Tuple

  • Tuple is also a sequence of objects which cannot change
items = (1,2,3)
## allowed
print(items)

for item in items:
    print(item)

len(items)

Leave a Comment

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

About learningthoughtsadmin