12

I have the following program. I am trying to understand list comprehension and set comprehension:

mylist = [i for i in range(1,10)]
print(mylist)

clist = []

for i in mylist:
    if i % 2 == 0:
        clist.append(i)


clist2 = [x for x in mylist if (x%2 == 0)]

print('clist {} clist2 {}'.format(clist,clist2))

#set comprehension
word_list = ['apple','banana','mango','cucumber','doll']
myset = set()
for word in word_list:
    myset.add(word[0])

myset2 = {word[0] for word in word_list}

print('myset {} myset2 {}'.format(myset,myset2))

My question is why the curly braces for myset2 = {word[0] for word in word_list}.

I haven't come across sets in detail before.

codeforester
  • 39,467
  • 16
  • 112
  • 140
liv2hak
  • 14,472
  • 53
  • 157
  • 270

2 Answers2

28

Curly braces are used for both dictionary and set comprehensions. Which one is created depends on whether you supply the associated value or not, like following (3.4):

>>> a={x for x in range(3)}
>>> a
{0, 1, 2}
>>> type(a)
<class 'set'>
>>> a={x: x for x in range(3)}
>>> a
{0: 0, 1: 1, 2: 2}
>>> type(a)
<class 'dict'>
Synedraacus
  • 975
  • 1
  • 8
  • 21
7

Set is an unordered, mutable collection of unrepeated elements.

In python you can use set() to build a set, for example:

set>>> set([1,1,2,3,3])
set([1, 2, 3])
>>> set([3,3,2,5,5])
set([2, 3, 5])

Or use a set comprehension, like a list comprehension but with curly braces:

>>> {x for x in [1,1,5,5,3,3]}
set([1, 3, 5])
Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 1
    What do you mean by "From python3.6, sets are ordered"? Can you share the link? I can't find the documentation that says sets are ordered. [Documentation](https://docs.python.org/3.8/library/stdtypes.html#set-types-set-frozenset) says it is an "unordered collection". – ywbaek Mar 19 '20 at 15:41
  • 3
    @oldwooki, actually , you are right. I don't know why, but I mistaked or extrapolated this with the dicts [that they have insertion order](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) Let me revert this. And thanks for pointing out!! – Netwave Mar 20 '20 at 10:40