words = ['a', 'an', 'the', 'are', 'articles']for word in words[:-1]:print(word, end =',')print(words[-1])
a,an,the,are,articles
words = ['a', 'an', 'the', 'are', 'articles']for i inrange(len(words)):if i !=len(words) -1:print(words[i], end =',')else:print(words[i])
a,an,the,are,articles
Find length of a list
L = [1.0, 3.5, 10.9, 5.3, -10.3]print(len(L))
5
Determine presence of element in a list
L = ['good', 'random', 'better', 'best']value ='random'print(value in L)
True
Remove an element from a list
L.remove(value) removes the leftmost occurrence of value from the list L if it exists. This operation is in-place. It throws an error if value is not present in L. Here is a graceful way of removing an element.
L = ['good', 'random', 'better', 'best']value ='random'if value in L: L.remove(value)print(L)
L = [10, 5, 3, 4, 10, 6, 9, 10]value =10while value in L: L.remove(value)print(L)
[5, 3, 4, 6, 9]
The reason we use L.copy() is to make sure that we don’t modify the list while we are iterating over it.
L = [10, 5, 3, 4, 10, 6, 9, 10]value =10for x in L.copy():if x == value: L.remove(value)print(L)
[5, 3, 4, 6, 9]
Find index of an element in a list
L.index(value) returns the index of the leftmost occurrence of value if it is present in the list. It will throw an error if value is not present in L. Here is a graceful way to express this:
L = [10, 20, 30, 40, 50]value =30if value in L: index = L.index(value)print(index)