I have created 2 lists, one which list comprehension and other using iteration. The second list started as an empty list, so it must have a different location in memory. So, ==
should return False
, but it returns True
. Notice that the memory location is different(2nd print call):
my_list = [x*2 for x in range(1, 10, 1)]
new_list = []
for item in range(1, 10, 1):
new_list.append(item * 2)
print(my_list == new_list) # True
print(hex(id(my_list)) == hex(id(new_list))) #False
Please explain why this is?
Simply because those are the semantics of Python's list comparisons with the ==
operator.
If you do want reference comparison, use the is
operator – in general, you never do want reference comparison though.
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.