0

I am new to python and things are little why's and how's. Just got to know "SETS" in python and I seem can't print it out the same order as I declare it. my code:

myPersonels = {"Haime", "Brian", "Ryan", "Jonathan", "Patrick", "Robert", 
               "Renzo", "Rjay", "Daniel", "Angelo"}

print(myPersonels)

output:

 {'Rjay', 'Daniel', 'Jonathan', 'Robert', 'Ryan', 'Renzo', 'Brian', 'Haime', 
 'Angelo', 'Patrick'}

I tried the sorted() method but it gives me the alphabetically order and that's not what I want. I want it to print the same order as I declare it. How can I do that? Any help will be much appreciated thanks.

Joseph Reyes
  • 69
  • 1
  • 3
  • 10

1 Answers1

0

Don't use a set -- use a list (or tuple if you will never change the values or length), which retains the ordering.

In [2]: myPersons = ["Haime", "Brian", "Ryan", "Jonathan", "Patrick", "Robert", 
   ...:              "Renzo", "Rjay", "Daniel", "Angelo"]  ## this is a list
   ...: print(myPersons)
   ...:                
   ['Haime', 'Brian', 'Ryan', 'Jonathan', 'Patrick', 'Robert', 'Renzo', 'Rjay', 'Daniel', 'Angelo']
Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • Well it depends what they want, if they want to avoid duplicates and do O(n) membership testing then a list or tuple is not suitable – Chris_Rands Apr 25 '17 at 13:22
  • @Chris_Rands premature optimization &c &c – Andrew Jaffe Apr 25 '17 at 13:25
  • It's not just about optimization Andrew, the output will be different if they ever have duplicate names – Chris_Rands Apr 25 '17 at 13:28
  • @Chris_Rands yes, but the easiest way to ensure that the input order is identical to the output order (which I take to mean including duplicates, but perhaps I am wrong!) is to use a list. Unless the OP also wants to de-duplicate, a list does exactly what is requested. – Andrew Jaffe Apr 25 '17 at 13:31