To detect do we have specific element in list we can use simple if statement - this is "yes or no" situation:
names =["Michael", "Samantha", "Anastasia", "John"]
if "Samantha" in names:
print("Samantha is there")
Result:
Samantha is there
>>>
What if Samantha is not element of list:
names =["Michael", "Anastasia", "John"]
if "Samantha" in names:
print("Samantha is there")
else:
print("Samantha is not there")
Result:
Samantha is not there
>>>
If we create multiple lists based on one original list, all changes will replicate to those lists, too:
names =["Michael", "Samantha", "Anastasia", "John"]
a = names
b = names
c = names
names[0] = "New Name"
print(names)
print()
print(a)
print(b)
print(b)
Result:
['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
['New Name', 'Samantha', 'Anastasia', 'John']
>>>
To delete all elements, there's dedicated clear()
function:
names =["Michael", "Samantha", "Anastasia", "John"]
names.clear()
print(names)
Result:
[]
>>>
To delete whole list, use del()
function:
names =["Michael", "Samantha", "Anastasia", "John"]
#List destruction
del names
You can't print from something you destroyed:
names =["Michael", "Samantha", "Anastasia", "John"]
del names
print(names)
Result:
Traceback (most recent call last):
File "C:\Python38-64\ARCHIVE\learning-python.py", line 4, in <module>
print(names)
NameError: name 'names' is not defined
>>>
In next tutorial, we will learn about Tuples.
No comments:
Post a Comment