Check if list contains unique elements or not [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to check if a list is composed of unique elements.
For example: [1,1,1], [4,4,4,4] or [2].
List can contain any value but it must be unique throughout the list.

You can use set() to get unique elements in the list and use len() to get the count of elements in your set. If it returns length as 1, then you have only one unique element in your list:
>>> my_list = [1,1,1]
>>> len(set(my_list))
1
However above solution is not performance efficient. In case your list is huge, you should write your own function to check this efficiently as:
def is_unique(my_list):
first_elem = my_list[0]
for elem in my_list[1:]:
if elem != first_elem:
return False
return True
Test runs:
>>> is_unique([1,1,2])
False
>>> is_unique([1,1,1])
True

Related

Returning index with list comprehension [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have two lists as:
main = [[1,2,3,4],[3,1,2,4],[4,3,1,2],[1,2,3,4],...]
and
lookup = [[3,1,2,4],[1,2,3,4],[4,3,1,2],...]
I want to return a list of indices where each element of main list is located in lookup list. Assume every unique row of main is included in lookup. For the visible part of the above example the result should be indices = [2,0,2,1]. List comprehension solutions are expected, since I already coded this with for loops.
P.S. Elaboration
[1,2,3,4],[3,1,2,4],[4,3,1,2],[1,2,3,4] are lists in main list. For every list in main list, return the index for an exact match in lookup list. 1st list element of main which is [1,2,3,4] is at the index 1 of lookup list, 2nd is at the index 0, 3rd is at 2 and last one is at 1. This makes indices=[2,0,2,1]. Sorry for not asking cleaner way.
You could create a dictionary with the unqiue values and their respective index using enumerate for the iterable "lookup".
main = [[1,2,3,4],[3,1,2,4],[4,3,1,2],[1,2,3,4]]
lookup = [[3,1,2,4],[1,2,3,4],[4,3,1,2]]
dic_lookup = {str(lst):i for i, lst in enumerate(lookup)}
lst_index = [dic_lookup.get(str(lst)) for lst in main]
print(lst_index)
#Out[5]: [1, 0, 2, 1]
Try this:
result = [ main.index(e) for e in lookup ]
Explanation:
main.index(e) looks for the first occurrence of e in main and returns its index. And the list comprehension does this for every element e in lookup.

Check if one 2d lists contains all elements of another 2d list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I would like to check if one 2d lists(list of lists) contains all elements of another 2d list. Assume the lists are supposed to be identical and sorted the same way but one entry is missing from the second list. I want the program to return the index of where the missing entry should be. I know how to do this for 1d lists, but this doesn't work for 2d lists. My idea was something like this, but it doesn't work for 2d lists:
list1 = [[1,2],[3,4],[5,6],[7,8],[8,9]]
list2 = [[1,2],[3,4],[7,8],[8,9]]
present = True
i = 0
while present == True:
for val in list1: #list1 is the full list
if val in list2: #list2 is the list missing an element
present = True
else:
present = False
print("missing value")
print(i)
i+=1
How can I make this work for 2d lists?
you can try using a single run through say, list A as a nested loop, and compare A[i][j] to B[i][j] at each iteration. If at any point they are not the same, or the list length is not the same, you can conclude that they arent the same.
for i in A:
for j in i:
if A[i][j] != B[i][j]:
break

How to check if a list contains items from another lists sublist? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I know this question has been asked several times here and I went through most of them but for some reason I am unable to utilise those solutions for my current issue.
I have a list with 11 sublists:
list_a = [[1,2,3],[2,3,4],[3,4,5].....[11,12,13]]
I also have a randomly generated list of length 9 within the range of 1 and 13:
list_b = [1,4,7,8,2,3,8,9]
I want to create a function that iterates through the sublists of list_a and returns true only if all the items within the sublist are present in list_b. I tried the 'all' function but it doesn't seem to work in my case here as it takes all the items within the list and not the sublist.
for i in list_a:
if all(a in i for a in list_b):
print ('Yes')
Thank you in advance.
You just got your all() logic twisted around. You need to check if each item in the sublist is in list_b (rather than checking if each item in list_b is in the sublist).
Change your all() logic to:
all(a in list_b for a in i)
As an aside, it would be a bit more efficient and simplify things if you changed list_b to a set.
Your thinking is right, but you are checking if elements in list_b exist in sublists of list_a, while your requirement is the inverse of it. You can use set operations here:
>>> list_a = [[1,2,3],[2,3,4],[3,4,5],[11,12,13]]
>>> list_b = [1,4,7,8,2,3,8,9]
>>> all(set(a).issubset(set(list_b)) for a in list_a)
False
or
>>> list_a = [[1,2,3],[2,3,4],[3,4,8]]
>>> all(set(a).issubset(set(list_b)) for a in list_a)
True

Returning duplicate tuples that match at a number of different indices [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have tuples nested in a list i.e. [(0,1,2,3,4,5,6,7), (etc)].
I'm trying to return the tuples that are matching at index 0 & 1, and 3 to 5 (and to keep the ordering of the data inside the tuple)
So with the code below I'm trying to remove the duplicates, then with the result I'm comparing this to the original list to identify the duplicates removed:
seen = set()
seen_add = seen.add
newL = []
for a in myList:
if a[:2] not in seen and not seen_add(a[:2]):
if a[3:6] not in seen and not seen_add(a[3:6]):
newL.append(a)
result = list(set(myList) - set(newL))
for i in result: print i
But the first part removes a tuple that doesn't even have a duplicate.
N.B. The code for removing the first two elements came from here (by Martijn Pieters): Removing Duplicates from Nested List Based on First 2 Elements; but removing additional elements resulted in the aforementioned 'error'.
To return the duplicates (this code follows the answer by #unutbu)
for i in result:
for e in newL:
if i[:2]==e[:2]:
if i[3:6]==e[3:6]:
print e, i
If you want to regard elements as matching when a[:2]+a[3:6] is the same, then you need to add
a[:2]+a[3:6] to seen, rather than a[:2] and a[3:6] separately:
seen = set()
seen_add = seen.add
newL = [a for a in myList
if a[:2]+a[3:6] not in seen
and not seen_add(a[:2]+a[3:6])]
newL will then contain "unique" elements from myList, with the order preserved. Note that calling set(myList) will destroy the order of the items in myList, so
result = list(set(myList) - set(newL))
will contain the duplicate elements, but the order will not be preserved.

Part of List into String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
ok looks like many did not understand the question. i will make it more clear.
i got a list:
List_1 = [1,2,3,4,5,6,7,8,9]
and what i do in my program is that if i press 1 that will make List_1[0] into X or what ever number i press, it turns it into an X. my list has 9 numbers total.
What i want to do, is that IF 3 specific numbers are converted into X then the program will move on.
so if i end up with:
List_1 = [1,'X',3,4,'X',6,'X',8,9]
then the program will move on.
If you need a contiguous set (such as the first three entries in your original question) use slice syntax:
list_2 = a[:3]
If you need only those elements from a specific set, use a comprehension:
stuff_i_need = [1, 'gg']
list_2 = [x for x in L if x in stuff_i_need]
(although, if you know what you need and it is a very small list, then just manually accessing the locations in the list that contain the elements you need is fine).
If you want to make a string of some contents of the list, one option is to just concatenate them yourself and wrap the elements with the string constructor str:
str(L[0]) + str(L[3])
Another way to do the same thing is:
import operator
reduce(operator.add, map(str, L))
# Also, just replace L with any of the slicing or accessing mentioned above.
Use a slice, as mentioned the other answers and comments. But if the indices are non-contiguous you can use a list comprehension together with enumerate:
>>> [x for i, x in enumerate(a) if i in [0, 1, 3]]
[1, 'X', 'X']
Update
The question changed, asking instead how to take different parts of a list and join them into a string. A small modification of the above:
>>> "".join(str(x) for i, x in enumerate(L) if i in [0, 3])
'1gg'

Categories