Last active
July 19, 2021 05:53
-
-
Save Fitzy1293/769ef67986e68cd2364765918a98d4a7 to your computer and use it in GitHub Desktop.
don't append to lists like this please
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def append_10(the_list=None): | |
if the_list is None: | |
the_list = [] | |
the_list.append(10) | |
return the_list | |
original_list = [4, 5] | |
print('unused list in top level scope') | |
print('\toriginal_list: ', original_list, sep='\t') | |
updated_list = append_10(the_list=original_list) | |
print('appending 10 to list argument in a function') | |
print('\tupdated_list: ', updated_list, sep='\t') | |
print('\toriginal_list:', original_list, sep='\t') | |
original_list.append(15) | |
print('appending 15 to the orginal in top level scope') | |
print('\toriginal_list:', original_list, sep='\t') | |
print('\tupdated_list:', updated_list, sep='\t') | |
updated_list.append(20) | |
print('appending 20 to the updated in top level scope') | |
print('\toriginal_list:', original_list, sep='\t') | |
print('\tupdated_list:', updated_list, sep='\t') | |
print('\nThe updated list is a reference to the orgiginal list.') | |
print('Changing values of the orgiginal_list means you change the value of the updated_list.') | |
print('Changing values of the updated_list **also** means you change the value of the original_list.') | |
print('Generally don\'t append to the list you enter as an argument to a function!' ) | |
print('append_10() default behavior', append_10(), sep='\n\t') | |
print('As you can see this is different!') | |
print('append_10() again, default behavior', append_10(), sep='\n\t') | |
print('A new list is initialized each time in the scope of the function') | |
print('NOT modifying the original_list in the outer scope.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment