Set & List Comprehension’s in Python
On this page
Set & List Comprehension’s in Python
Sets
- A set is an unordered collection
- Eliminates duplicate entries.
- Empty set
my_set= set() my_set = {1,2,3,4}
:-
- add
my_set.add(5) - remove /delete
my_set.remove(3) # Raises KeyError if element notfound
my_set.discard(3) # Does nothing if element not found
my_set.clear() # Removes all elements
- Length
len(my_set)
set operations
- union
seta.union(setb)orseta | setb - Intersection
seta.intersection(setb)orseta & setb - Difference
seta.difference(setb)orseta - setb - Symmeteric difference (unique elements of both sets)
seta.symmetric_difference(setb)orset ^ setb
Advanced List
- creating list in single line
[expression for item in iterable if condition]
eg : sqaures = [x*x for x in range(0,9) if x%2 == 0]
- Slicing list
list[start:end:step] - Reverse/sort
sort(), reverse() - Nested List {list in list : multidimensional list }
[[1,2],[3,4]]
- List Copy
list.copy() list.deepcopy()
- map / filter
lambda expressionmap( lambda function, list/range) filter(lamda condition , )
More in Python
See all →- Linear Regression Namaste doston! Aaj hum baat karenge ek bahut hi interesting topic ke baare mein – Linear Regression. Yeh Data Science ki duniya ka ek aisa...
- Learn Python Programming in 2024 Introduction to Python: What is Python?: Python is a high-level, interpreted programming language known for its simplicity and readability....
- Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are the square of the keys. Sample Dictionary{1: 1, 2: 4, 3: 9, 4...
- Write a Python program to combine two dictionaries by adding values for common keys. Write a Python program to combine two dictionaries by adding values for common keys. d1 = {‘a’: 100, ‘b’: 200, ‘c’:300} d2 = {‘a’: 300, ‘b’:...
- Write a program that prompts the user to input a positive integer. It should then output a message indicating whether the number is a prime number. A prime number is a number that is evenly divisible only by...
- Floyd’s triangle is a right-angled triangular array of natural numbers as shown below: Write a program to print the Floy’d triangle. # Floyd's Triangle row = int(input("Rows you want : ")) num = 1 print("Floyd's Triangle") for...