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.
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.
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.
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.
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.
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'>
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With