Python Fundamentals - Python Sets
https://www.gcreddy.com/forum/viewtopic.php?f=101&t=1736
Python Fundamentals - Python Sets
What is Set?
Set in Python is a data structure equivalent to sets in mathematics. It may consist of various elements; the order of elements in a set is undefined.
Python set is a collection which is unordered and unindexed. In Python, sets are written with curly brackets.
Example
Create a Set:
fruits= {"apple", "banana", "cherry"}
print(fruits)
Operations on Python Sets
1) Access Items
We cannot access items in a set by referring to an index, since sets are unordered the items has no index.
But we can loop through the set item
Example 1:
Loop through the set, and print the all values
fruits = {"apple", "banana", "cherry"}
for x in fruits:
print(x)
Example 2:
Check if "banana" is present in the set:
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)
Note: It will print True/False like result
2) Change Items
Once a set is created, we cannot change its items, but we can add new items.
3) Add Items
i) To add one item to a set use the add() method.
ii) To add more than one item to a set use the update() method.
Example 1:
Add an item to a set, using the add() method:
fruits = {"apple", "banana", "cherry"}
fruits.add("orange")
print(fruits)
Example 2:
Add multiple items to a set, using the update() method:
fruits = {"apple", "banana", "cherry"}
fruits.update(["orange", "mango", "grapes"])
print(fruits)
4) Get the Length of a Set
To determine how many items a set has, use the len() method.
Example
Get the number of items in a set:
fruits = {"apple", "banana", "cherry"}
print(len(fruits))
5) Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example 1:
Remove "banana" by using the remove() method:
fruits = {"apple", "banana", "cherry"}
fruits.remove("banana")
print(fruits)
-----------------------------------
Example 2:
Remove "banana" by using the discard() method:
fruits = {"apple", "banana", "cherry"}
fruits.discard("banana")
print(fruits)
Note: If the item to remove does not exist, discard() will NOT raise an error.
-------------------------
Example 3:
Remove the last item by using the pop() method:
fruits = {"apple", "banana", "cherry"}
x = fruits.pop()
print(x)
print(fruits)
Note: Sets are unordered, so when using the pop() method, you will not know which item that gets removed.
---------------------------------------
Example 4:
The clear() method empties the set:
fruits = {"apple", "banana", "cherry"}
fruits.clear()
print(fruits)
-----------------------------
Example 5:
The del keyword will delete the set completely:
fruits = {"apple", "banana", "cherry"}
del fruits
print(fruits)
Note: It will show error
6) Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or the update() method that inserts all the items from one set into another:
Example 1:
The union() method returns a new set with all items from both sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)
--------------------------
Example 2:
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Python Fundamentals - Python Sets», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.