I have a group of lists
embed_list = []
hreflist = []
nationality_list = []
Movie_NAMEnYEAR_strap_list = []
actors_list=[]
poster_url = []
list_of_genres = []
and after adding some strings to them, I want to purge them, so I tried the following
1st I tried using .clear() but I got the following error
'str' object has no attribute 'clear'
then I tried re-initiating the list value to [] using a function
def purging_lists():
embed_list = []
hreflist = []
nationality_list = []
Movie_NAMEnYEAR_strap_list = []
actors_list=[]
poster_url = []
list_of_genres = []
but it wasn't effective
CodePudding user response:
The clear
method should work fine for your purpose. Just make sure to apply it to the whole list, not individual items. For example:
actors_list = []
actors_list.append('Jeff Bridges')
actors_list.append('John Goodman')
print(actors_list) # Output: ['Jeff Bridges', 'John Goodman']
# Wrong:
actors_list[0].clear()
# AttributeError: 'str' object has no attribute 'clear'
# Right:
actors_list.clear()
print(actors_list) # Output: []
Your function did not have the desired effect, because you created empty lists as new local variables inside the function, rather than overwriting the existing lists. To make this idea work, you would have to declare that you are referring to the lists that exist outside the function, using the global
statement, e.g.:
def purging_lists():
global actors_list
actors_list = []
But that is unnecessarily convoluted. Just use list.clear()
, as outlined above.