-1

I am using list in python program, following is the code

x = [['Port', 'Status']]
x.append({11,'Open'})
x.append({22,'Close'})
x.append({356,'Open'})
x.append({1024,'Close'})
x.append({512,'Open'})
x.append({777,'Close'})
print(x)

the output of above is

    [['Port', 'Status'], set([11, 'Open']), set(['Close', 22]), set(['Open', 356]), set([1024, 'Close'])
, set([512, 'Open']), set([777, 'Close'])]

Problem is that the output is not in the order It was entered. i.e on some cases string is appearing before integer vice versa on other cases. Please help.

  • From [\[Python\]: set definition](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset): _A set object is an **unordered** collection of distinct hashable objects_. To keep the order use *list*s (as you do for the header - 1st element), or *tuple*s instead of *set*s. – CristiFati Apr 12 '17 at 10:55

4 Answers4

1

set is an unordered, you can use tuple or list instead:

x = [['Port', 'Status']]
x.append((11,'Open'))
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
0

A set is an unordered collection with no duplicate elements

    for example:
    >> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
    >> print(basket)         # see that duplicates have been removed
    >> {'orange', 'banana', 'pear', 'apple'}

you can see that order has changed.

You are appending {11,'Open'} which is set and can change order at run time. so better use ordered data structure if you want to maintain the order.

for example use like this:
>> x.append((11, 'Open'))
or 
>> x.append([11, 'Open'])
JkShaw
  • 1,927
  • 2
  • 13
  • 14
0

Simply use [] instead of {} as jyotish implied.

dylan_fan
  • 680
  • 1
  • 5
  • 18
0

You're using a set as a container for the values, which do not have a fixed order.

Instead, you can use a tuple (e.g. (11, 'Open')) or another list (e.g. [11, 'Open']). But a tuple is probably a better match here.

Arjen
  • 1,321
  • 8
  • 10