C= ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
how do i make it into a new variable like this .?
Cnew=['a','b','c']
is there a function or anything i can do?
C= ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
how do i make it into a new variable like this .?
Cnew=['a','b','c']
is there a function or anything i can do?
I'd turn the list into a set:
C= ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
Cnew = set(C)
Set's work very much like lists, but they only allow one of each element, which is what you want. However, if you really want a list, simply convert the set back to a list via the list
function.
C= ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
cNew = []
for value in C:
if value not in cNew:
cNew.append(value)
print(cNew)
If you want to preserve order and remove duplicates, here's one approach using collections.OrderedDict
:
from collections import OrderedDict
C= ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
new_C = list(OrderedDict.fromkeys(C).keys())
Although it seems like this would also suffice for your use case:
new_C = sorted(set(c))
It's also worth noting, if you didn't already know, that, lookups (checking for membership) in a list
object (the data structure from your desired output), are of time-complexity O(n)
, while lookups for set
objects are O(1)
. It all depends on what you're trying to do with your output, of course...
You can use set()
, so:
newset = set(c)
print(new_set)