I have a code that displays the number of identical names in the list, but I also need these names to go to the new list and the output would be an array with duplicate elements. Help me please. Example: at the input ['Alex', 'Ighor', 'Alex', 'Djin'] at the exit ['Alex', 'Alex'] We need a function without using count.

list_of_student = ['Alex', 'Ighor', 'Alex', 'Djin'] def count_of_student(student): return list_of_student.count(student) 
  • It is necessary to remove the code not related to the question from the question and to formulate the task more clearly. Give an example of the input data and the desired result. Now it is not clear what is required and what is the problem. - Enikeyschik
  • Thanks, corrected - Sofanchik

2 answers 2

 list_of_student = ['Alex', 'Ighor', 'Alex', 'Djin'] [ i for i in list_of_student if list_of_student.count(i)>1 ] ['Alex', 'Alex'] 

 def count_of_student(student): if list_of_student.count(student)>1: return student [ count_of_student(i) for i in list_of_student if count_of_student(i)] ['Alex', 'Alex'] 

 class Student(): def count_of_student(self, student): if list_of_student.count(student)>1: return student s = Student() new_list = [ s.count_of_student(i) for i in list_of_student if s.count_of_student(i)] print(new_list) ['Alex', 'Alex'] 
  • Sorry, it does not work, but thanks anyway ... - Sofanchik pm
  • and what exactly does not work? - S. Nick
  • It does not print anything) And the problem is that the list_of_student is strings, we cannot compare them to int ... I was just given the task to create a school at the moment I am working on creating student lists, and if there are similar ones, they need to be output in a separate list ... well, in general, this is probably not so important - Sofanchik 5:14
  • plus, all these methods will be done in classes ... - Sofanchik
  • I added your method to the class - S. Nick

To accomplish the task, it is necessary to run through the entire list for each element of the list to identify identical elements, if count not appropriate, len can be dispensed with:

 a = [1, 1, 2, 3, 3, 4] print [i for i in a if len([j for j in a if j == i]) > 1] # [1, 1, 3, 3] 
  • You helped me a lot, thanks) - Sofanchik