How can I print the elements (non repetitive) in a list
x=[1,1,1,1,2,2,2,"a","a","a","b","b"]
what you are looking for is a function to get the unique elements of a list. In general what you want is a set
, which by definition only contains unique elements.
Are there any functions in Python that can do it? Or, how do I write a for loop to do it?
Python offers several ways to do this, depending on your specific needs one or the other is more appropriate. Here are a few examples:
# order and selection don't matter
print set(x)
# preserve item order
print dict(zip(x, x)).keys()
# filter, order not preserved
print set(filter(lambda s : True if isinstance(s, str) else False, x))
# filter, preserve order
print (lambda x : [s for s in dict(zip(x,x)).keys() if isinstance(s, str)])(x)
what if the case is that the list is pretty long and I don't even know how many kinds of elements in the list?
Theoretically, if you don't know what is in the list, there is no way other than to look at each element, if you want to be sure.
If you have some knowledge about the list, say you know there is at least two elements of each kind, and in sequence as in your example, you can skip a few elements and get at least an approximation of your list.
This could be interesting if the list is huge (although I doubt it makes any real difference, because the list is already in memory). As an example:
# c is the number of items that at least appear in sequence. here
# we only touch every other element, so we have reduced the number
# of accesses to x by n/2.
(lambda x, c : set(( x[i] for i in range(0, len(x), c) )))(x, 2)
=> {1, 2, 'a', 'b'}