Tuples and sets
This commit is contained in:
39
src/basic/tuples_and_sets.py
Normal file
39
src/basic/tuples_and_sets.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Tuples
|
||||||
|
# tuples are immutable
|
||||||
|
# tuples are ordered and we can access their elements using their index values
|
||||||
|
# Tuples cannot be appended or extended
|
||||||
|
# We cannot remove items from a tuple once it is created.
|
||||||
|
# tuples contain duplicate elements
|
||||||
|
|
||||||
|
tup = (10, 20, 30, 10, 20, 20, 30)
|
||||||
|
print(tup)
|
||||||
|
|
||||||
|
print(tup[0]) # 10
|
||||||
|
|
||||||
|
# del tup[0] # gives TypeError: 'tuple' object doesn't support item deletion
|
||||||
|
|
||||||
|
# tup[1] = 100 # TypeError: 'tuple' object does not support item assignment
|
||||||
|
|
||||||
|
|
||||||
|
# tuple with different datatypes
|
||||||
|
tup = ("immutable", True, 23)
|
||||||
|
print(tup)
|
||||||
|
|
||||||
|
|
||||||
|
# Python Sets
|
||||||
|
# Python set is an unordered collection
|
||||||
|
# sets are mutable
|
||||||
|
# unindexed and do not contain duplicates
|
||||||
|
# The order of elements in a set is not preserved and can change
|
||||||
|
|
||||||
|
set1 = {3, 1, 4, 1, 5, 9, 2, 2}
|
||||||
|
|
||||||
|
print(set1) # Output may vary: {1, 2, 3, 4, 5, 9}
|
||||||
|
# Add one item
|
||||||
|
set1.add(4)
|
||||||
|
|
||||||
|
# Add multiple items
|
||||||
|
set1.update([5, 6])
|
||||||
|
|
||||||
|
set1.remove(3)
|
||||||
|
print(set1)
|
||||||
Reference in New Issue
Block a user