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?

0

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

how do i access a set though? and it gives me Cnew {'a', 'c', 'b'} i want it to be in order , eventhough i can call a sort function
Use sorted with list. sorted(list(set(C))
is there any way i can do it without set function though? because my assignment really focus on algorithms
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...

4 Comments

the 2nd function is perfect dude thanks
is there any way i can do it without set function though? because my assignment really focus on algorithms
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"...
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])
1

You can use set(), so:

newset = set(c)
print(new_set)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.