Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension vs set comprehension

Tags:

python

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.

like image 544
liv2hak Avatar asked Dec 03 '15 06:12

liv2hak


People also ask

Can you use list comprehension with a set?

It is easy to use the list comprehensions in Python (or Python set or dictionary comprehensions). Besides lists, sets and dictionaries, it is also possible to use different data types like strings, tuples or even lambda functions.

What is meant by set comprehension?

Set comprehension is a mathematical notation for defining sets on the basis of a property of their members. Although set comprehension is widely used in mathematics and some programming languages, direct support for reasoning about it is still not readily available in state-of-the-art SMT solvers.

Is there set comprehension in Python?

The last comprehension we can use in Python is called Set Comprehension. Set comprehensions are similar to list comprehensions but return a set instead of a list. The syntax looks more like Dictionary Comprehension in the sense that we use curly brackets to create a set.

What is the difference between list comprehension and for loop?

List comprehensions are the right tool to create lists — it is nevertheless better to use list(range()). For loops are the right tool to perform computations or run functions. In any case, avoid using for loops and list comprehensions altogether: use array computations instead.


2 Answers

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'>
like image 102
Synedraacus Avatar answered Sep 18 '22 21:09

Synedraacus


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])
like image 37
Netwave Avatar answered Sep 18 '22 21:09

Netwave