Let start off by taking a look at the following code.
list = [1, 2, 3, 4, 5]
list_2= list
del list[1]
print(list_2)
Now the following code should return the results [1, 2, 3, 4, 5] right? Wrong, the code returns [1, 3, 4, 5]
This is because you are setting the list equal to the current location of the other list, not the list’s content. When the code looks at the location of the data for list_2 it looks in list since that is what list_2 is set to. In order to copy only the elements within a list the following code can be used list_var = list[start:stop]. The first element listed is where the list will begin, the second is the first element the list will not include. If both are left blank then this will indicate the entirety of the list’s contents will be copied.
Code:
list = [1, 2, 3, 4, 5]
list_2= list[:]
del list[1]
print(list_2)
Result:
[1, 2, 3, 4, 5]
Here’s another example with different values
list = [1, 2, 3, 4, 5]
list_2= list[2:4]
del list[3]
print(list)
print(list_2)
Result:
[1, 2, 3, 5]
[3, 4]
Now for the use of the in and not in operators with lists, it is rather simple, element in list_name and element not in list_name how it works is the code will check to see if the element is or isn’t in the list and return the appropriate result, true or false.
Code:
list = [1, 2, 3, 4, 5]
print(1 in list)
print(7 not in list)
print(6 in list)
Result:
True
True
False
Here is a more interesting use of the in and not in operator, the following code will go through each item in the list and add unique numbers to a new list and print the result. I’ve also added the sort method as well to show how multiple operators and methods can be used to sort the list into unique elements and sort them in ascending order!
Code:
numbers = [1, 2, 2, 2, 4, 3, 3, 6, 4, 5, 9, 6, 6, 7, 7, 8, 9, 10]
numbers_new = []
for i in numbers:
if i not in numbers_new:
numbers_new.append(i)
print(numbers_new)
numbers_new.sort()
print(numbers_new)
Result:
[1, 2, 4, 3, 6, 5, 9, 7, 8, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]