简体   繁体   中英

Python - Question about initialising lists with [None] versus with just []

I'm currently looping over some lists of strings to populate a new list. Originally I had:

z_locations = ['50', '100', '150', '250', '500']
path = [None]
for counter, value in enumerate(z_locations):
   path.append('Desktop/Data/z_' + value)

My list path would come out as a list of length 6, with the first element in my new list path would be simply NoneType . I can fix this by changing to:

z_locations = ['50', '100', '150', '250', '500']
path = []
for counter, value in enumerate(z_locations):
   path.append('Desktop/Data/z_' + value)

Which removes the NoneType being the first element and only copies as I had originally intended. However, I am unsure why this was happening in the first place. I have not encountered this NoneType before in creating new lists. Could someone please enlighten me as to why this happens?

Thanks.

That is happening because append adds an element to the end of the list. Your list all ready has None in it so any elements you add are going to be put after it, like this [None, ...] . Therefore when you get the first element, it gives you None .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM