Содержание
Кортежи
Кортеж тоже является последовательностью и создается элементами разделёнными запятыми:
>>> companies = «Google», «Microsoft», «Tesla» >>> companies (‘Google’, ‘Microsoft’, ‘Tesla’)
1 2 3 |
>>>companies=»Google»,»Microsoft»,»Tesla» >>>companies (‘Google’,’Microsoft’,’Tesla’) |
При определении непустого кортежа скобки не обязательны, но они становятся обязательными когда кортеж является частью большего выражения. Пустой кортеж создаётся пустой парой скобок:
>>> companies = () >>> type(companies) <class ‘tuple’>
1 2 3 |
>>>companies=() >>>type(companies) <class’tuple’> |
При определении кортежа с одним элементом запятая за ним обязательна.
>>> company = «Google», >>> type(company) <class ‘tuple’>
>>> company = («Google»,) >>> type(company) <class ‘tuple’>
1 2 3 4 5 6 7 |
>>>company=»Google», >>>type(company) <class’tuple’> >>>company=(«Google»,) >>>type(company) <class’tuple’> |
Пропуск запятой означает что задано обычное значение, не кортеж.
>>> company = («Google») >>> company ‘Google’
>>> type(company) <class ‘str’>
1 2 3 4 5 6 |
>>>company=(«Google») >>>company ‘Google’ >>>type(company) <class’str’> |
Кортежи индексируются как списки, но неизменямы.
>>> companies = («Google», «Microsoft», «Palantir») >>> companies ‘Google’ >>> companies = «Boeing» Traceback (most recent call last): File «<stdin>», line 1, in <module> TypeError: ‘tuple’ object does not support item assignment
1 2 3 4 5 6 7 |
>>>companies=(«Google»,»Microsoft»,»Palantir») >>>companies ‘Google’ >>>companies=»Boeing» Traceback(most recent call last) File»<stdin>»,line1,in<module> TypeError’tuple’objectdoes notsupport item assignment |
В тоже время, если элементом кортежа является изменяемые объект, такой как список, то он может быть изменен.
>>> companies = (, ) >>> companies (, ) >>> companies.append(«SpaceX») >>> companies (, )
1 2 3 4 5 6 |
>>>companies=(«lockheedMartin»,»Boeing»,»Google»,»Microsoft») >>>companies (‘lockheedMartin’,’Boeing’,’Google’,’Microsoft’) >>>companies.append(«SpaceX») >>>companies (‘lockheedMartin’,’Boeing’,’SpaceX’,’Google’,’Microsoft’) |
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Other Set Operations
We can test if an item exists in a set or not, using the keyword.
Output
True False
Built-in Functions with Set
Built-in functions like , , , , , , , etc. are commonly used with sets to perform different tasks.
Function | Description |
---|---|
all() | Returns if all elements of the set are true (or if the set is empty). |
any() | Returns if any element of the set is true. If the set is empty, returns . |
enumerate() | Returns an enumerate object. It contains the index and value for all the items of the set as a pair. |
len() | Returns the length (the number of items) in the set. |
max() | Returns the largest item in the set. |
min() | Returns the smallest item in the set. |
sorted() | Returns a new sorted list from elements in the set(does not sort the set itself). |
sum() | Returns the sum of all elements in the set. |
Recommended Posts:
- Python Sets
- Python | remove() and discard() in Sets
- Output of Python Programs | Set 24 (Sets)
- Python Set | Pairs of complete strings in two sets
- Python | sympy.sets.open() method
- Python | sympy.sets.Lopen() method
- Python | sympy.sets.Ropen() method
- Python program to count number of vowels using sets in given string
- Python program to find common elements in three lists using sets
- Cartesian Product of any number of sets
- Python program to check if the list contains three consecutive common numbers in Python
- Reusable piece of python functionality for wrapping arbitrary blocks of code : Python Context Managers
- Python — Read blob object in python using wand library
- Creating and updating PowerPoint Presentations in Python using python — pptx
- Python | Convert list to Python array
- Python | Index of Non-Zero elements in Python list
- twitter-text-python (ttp) module — Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | PRAW — Python Reddit API Wrapper
- Python | Merge Python key values to list
Other Python Set Methods
There are many set methods, some of which we have already used above. Here is a list of all the methods that are available with the set objects:
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all elements from the set |
copy() | Returns a copy of the set |
difference() | Returns the difference of two or more sets as a new set |
difference_update() | Removes all elements of another set from this set |
discard() | Removes an element from the set if it is a member. (Do nothing if the element is not in set) |
intersection() | Returns the intersection of two sets as a new set |
intersection_update() | Updates the set with the intersection of itself and another |
isdisjoint() | Returns if two sets have a null intersection |
issubset() | Returns if another set contains this set |
issuperset() | Returns if this set contains another set |
pop() | Removes and returns an arbitrary set element. Raises if the set is empty |
remove() | Removes an element from the set. If the element is not a member, raises a |
symmetric_difference() | Returns the symmetric difference of two sets as a new set |
symmetric_difference_update() | Updates a set with the symmetric difference of itself and another |
union() | Returns the union of sets in a new set |
update() | Updates the set with the union of itself and others |
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Списки
Список представляет собой упорядоченную последовательность элементов. Он очень гибкий и является одним из самых используемых типов в Python. Элементы списка не обязательно должны быть одного типа.
Объявить список довольно просто. Внутрь квадратных скобок помещаются элементы списка, разделённые запятой:
Мы можем использовать оператор для извлечения элемента (такая операция называется “доступ по индексу”) или диапазона элементов (такая операция назвается “извлечение среза”) из списка. В Python индексация начинается с нуля:
Списки являются изменяемым типом, т.е. значения его элементов можно изменить:
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Python NumPy
NumPy IntroNumPy Getting StartedNumPy Creating ArraysNumPy Array IndexingNumPy Array SlicingNumPy Data TypesNumPy Copy vs ViewNumPy Array ShapeNumPy Array ReshapeNumPy Array IteratingNumPy Array JoinNumPy Array SplitNumPy Array SearchNumPy Array SortNumPy Array FilterNumPy Random Random Intro Data Distribution Random Permutation Seaborn Module Normal Distribution Binomial Distribution Poisson Distribution Uniform Distribution Logistic Distribution Multinomial Distribution Exponential Distribution Chi Square Distribution Rayleigh Distribution Pareto Distribution Zipf Distribution
NumPy ufunc ufunc Intro ufunc Create Function ufunc Simple Arithmetic ufunc Rounding Decimals ufunc Logs ufunc Summations ufunc Products ufunc Differences ufunc Finding LCM ufunc Finding GCD ufunc Trigonometric ufunc Hyperbolic ufunc Set Operations
Set Methods
Python has a set of built-in methods that you can use on sets.
Method | Description |
---|---|
add() | Adds an element to the set |
clear() | Removes all the elements from the set |
copy() | Returns a copy of the set |
difference() | Returns a set containing the difference between two or more sets |
difference_update() | Removes the items in this set that are also included in another, specified set |
discard() | Remove the specified item |
intersection() | Returns a set, that is the intersection of two other sets |
intersection_update() | Removes the items in this set that are not present in other, specified set(s) |
isdisjoint() | Returns whether two sets have a intersection or not |
issubset() | Returns whether another set contains this set or not |
issuperset() | Returns whether this set contains another set or not |
pop() | Removes an element from the set |
remove() | Removes the specified element |
symmetric_difference() | Returns a set with the symmetric differences of two sets |
symmetric_difference_update() | inserts the symmetric differences from this set and another |
union() | Return a set containing the union of sets |
update() | Update the set with the union of this set and others |
Methods for Sets
Adding elements
Insertion in set is done through set.add() function, where an appropriate record value is created to store in the hash table. Same as checking for an item, i.e., O(1) on average. However, in worst case it can become O(n).
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
People: {'Idrish', 'Archi', 'Jay'} Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}
Union
Two sets can be merged using union() function or | operator. Both Hash Table values are accessed and traversed with merge operation perform on them to combine the elements, at the same time duplicates are removed. Time Complexity of this is O(len(s1) + len(s2)) where s1 and s2 are two sets whose union needs to be done.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Union using union() function {'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'} Union using '|' operator {'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}
Intersection
This can be done through intersection() or & operator. Common Elements are selected. They are similar to iteration over the Hash lists and combining the same values on both the Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union needs to be done.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Intersection using intersection() function {3, 4} Intersection using '&' operator {3, 4}
Difference
To find difference in between sets. Similar to find difference in linked list. This is done through difference() or – operator. Time complexity of finding difference s1 – s2 is O(len(s1))
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Difference of two sets using difference() function {0, 1, 2} Difference of two sets using '-' operator {0, 1, 2}
Clearing sets
method empties the whole set.
filter_none
editclose
play_arrow
linkbrightness_4code
chevron_right
filter_none
Output:
Initial set {1, 2, 3, 4, 5, 6} Set after using clear() function set()
However, there are two major pitfalls in Python sets:
- The set doesn’t maintain elements in any particular order.
- Only instances of immutable types can be added to a Python set.
С этим читают
- Методы строк в python
- Несколько подводных камней статической типизации в python
- Numpy.nonzero
- Кортежи и операции с ними
- Python write file/ read file
- Теория вероятностей на практике или знаете ли вы о random
- Python string isupper islower upper lower functions example
- Учебник по sqlite3 в python
- Traceback в python
- Python урок 4. списки или массивы в питоне