0
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?

Mohammad
  • 21,175
  • 15
  • 55
  • 84

3 Answers3

4

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.

Per the request of the OP

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)
Community
  • 1
  • 1
Neil
  • 14,063
  • 3
  • 30
  • 51
2

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...

blacksite
  • 12,086
  • 10
  • 64
  • 109
  • the 2nd function is perfect dude thanks – Handy Hasan Apr 23 '17 at 15:45
  • is there any way i can do it without set function though? because my assignment really focus on algorithms – Handy Hasan Apr 23 '17 at 15:47
  • Think about what you need to do. Go through each element in your list, check whether you've "seen" that elements before, and keep track of which elements have already been "seen"... – blacksite Apr 23 '17 at 15:49
  • im really stuck ! :( can you please make the function that i can access #for j in range(len(final)): #if final.count(final[j]) > 1: #if j!= len(final)-1: #if final[j]==final[j+1]: #veryfinal.append(final[j]) #else: #veryfinal.append(final[j]) – Handy Hasan Apr 23 '17 at 15:52
1

You can use set(), so:

newset = set(c)
print(new_set)
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253