This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 2 years ago.
How can I remove duplicates from this list?
x = [name, code]
Some elements of list has the same code:
list = [['cafe', '/fr/48349066'], ['cafe', '/fr/48349056'], ['cafe', '/fr/48349066']]
There's probably a more processing-efficient way to do this, but this is the way I've always done stuff like this:
for i in range(len(list)):
for j in range(len(list)):
if list[i][1] == list[j][1]:
list.pop(i)
There is a lot of ways to removing duplicates;
1-) The Naive Method;
new_list = []
for i in some_list:
if i not in new_list:
res.append(i)
2-) Using list comprehension;
new_list = []
[new_list.append(x) for x in some_list if x not in new_list]
3-) Using set();
some_list = list(set(some_list))
4-) Using collections.OrderedDict.fromkeys()
from collections import OrderedDict
new_list = list(OrderedDict.fromkeys(some_list))
Related
This question already has answers here:
Checking whether a string starts with XXXX
(5 answers)
Apply function to each element of a list
(4 answers)
Closed 3 months ago.
I have a list that I want to edit. For all the elements that start with '[x]', I want the list to remove those elements and place them into new list. But for the new list, in doing so, it should remove the '[x]' from the front of the elements.
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
list1 becomes:
list1 = ['midterm', 'school']
new list that was created from removing the elements that had '[x]' in the front:
new_list = ['final', 'gym', 'class']
I am new to coding and am having difficulties with this.
Since you are a beginner, the verbose way to do this is the following
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = []
for s in list1:
if s.startswith("[x]"):
new_list.append(s[3:])
print(new_list)
However, you can take advantage of Python's list comprehension to do it in a single line, like this
list1 = ['[x]final', '[x]gym', 'midterm', '[x]class', 'school']
new_list = [s[3:] for s in list1 if s[0:3] == "[x]"]
print(new_list)
Both methods yield ['final', 'gym', 'class']
This question already has answers here:
Different ways of clearing lists
(8 answers)
Closed 4 years ago.
list1 = [2,5,61,7,10]
list1.remove(list1[0:len(list1)-1])
print(list1)
I want to remove all elements from that list but it shows me syntax error.
Any idea how can I remove all elements and print the final result like []
To remove all list items just use the in-built .clear() function:
>>> list1 = [2,5,61,7,10]
>>> list1.clear()
>>> print(list1)
[]
>>>
If you want to remove all elements from a list, you can use the slice assignment:
list1[:] = []
But with list.remove(), you can only do it one-by-one:
for item in list(list1):
list1.remove(item)
Note I created a copy of list1 with the for loop because it's dangerous to modify what you're iterating over, while it's safe to modify the list while iterating over a copy of it.
To remove some of the items:
for item in list1[0:3]:
list1.remove(item)
Or just better yet, use slice assignment:
list1[0:3] = []
This question already has answers here:
Removing duplicates in lists
(56 answers)
Closed 5 years ago.
I have a list of strings in which there are a lot of repeated items. I would like to make a new list in which all items are present but there is only one occurrence of each item.
input:
mylist = ["hg", "yt", "hg", "tr", "yt"]
output:
newlist = ["hg", "yt", "tr"]
I actually have tried this code but did not return what I want:
newlist = []
for i in range(len(mylist)):
if mylist[i+1] == mylist[i]:
newlist.append(mylist[i])
You can simply use a set:
newlist = set(mylist)
Or, to retrieve exactly a list, but is can be useless depending what you are doing with:
nexlist = list(set(mylist))
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 years ago.
How do I convert a list of lists to a single list?
Input:
a=[['AA'], ['AE'], ['AH'], ['AO'],]
Desired output:
['AA','AE','AH','AO']
a=[['AA'], ['AE'], ['AH'], ['AO'],]
l=[]
for i in a:
l.extend(i)
print l
you could use comprehension list:
or using map and lambda functions
a=[['AA'], ['AE'], ['AH'], ['AO'],]
# open the item [0] with generators
Newa = [x[0] for x in a]
>>>['AA', 'AE', 'AH', 'AO']
see examples: http://www.secnetix.de/olli/Python/list_comprehensions.hawk
EDIT:
for i, value in enumerate(a):
a[i] = value[0]
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I want to delete word sabin from the array but it is showing some error...
array=["sabin","ram","hari","sabin"]
length=len(array)
for steps in range(length):
if(array[steps]=="sabin"):
print("removed=%s"%(array[steps]))
del array[steps]
length=len(array)
print(length)
you could do this with a list comprehesion:
array=["sabin","ram","hari","sabin"]
length=len(array)
array = [x for x in array if not x == 'sabin']
length=len(array)
The error that you are receiving is an IndexError. This is because you are removing values from the list, while still iterating over it. One possible solution is to use the remove method of the list object to remove instances of "sabin":
array=["sabin","ram","hari","sabin"]
to_remove = 'sabin'
while to_remove in array:
array.remove(to_remove)
print("removed=%s"%(to_remove))
print(len(array))
This avoids the IndexError since it is not dependent on the index staying the same throughout the loop.
You can use filter too!
my_list = ["sabin","ram","hari","sabin"]
print(my_list)
>>> ['sabin', 'ram', 'hari', 'sabin']
my_list = filter(lambda x: x != 'sabin', my_list)
print(my_list)
>>> ['ram', 'hari']