In this article, we will explore common operations that can be applied to collections like tuples and dictionaries in Python. The video tutorial linked below demonstrates these operations in action.
Click here to watch the video tutorial
Key Concepts Explanation
Tuple Operations
Tuples are immutable sequences in Python. Here are some key operations that can be performed on tuples:
- Check if an element exists in the tuple using the
in
keyword:
t = (1, 2, 3, 4)
1 in t
5 in t
- Get the number of elements in the tuple using the
len
function:
len(t)
- Sort the elements in the tuple (original tuple remains untouched) using the
sorted
function:
sorted(t, reverse=True)
- Perform arithmetic operations like
sum
,min
,max
, etc:
sum(t)
Dictionary Operations
Dictionaries are unordered collections of key-value pairs in Python. Here are some common operations on dictionaries:
- Check if a key exists in the dictionary using the
in
keyword:
d = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
1 in d
5 in d
'a' in d
- Get the number of key-value pairs in the dictionary using the
len
function:
len(d)
- Sort the keys in the dictionary (original dictionary remains untouched) using the
sorted
function:
sorted(d)
- Perform arithmetic operations like
sum
,min
,max
, etc (these operations are performed on keys):
sum(d)
Hands-On Tasks
Here are some hands-on tasks for you to try out:
- Create a tuple with your favorite numbers and check if a specific number is present in the tuple.
- Create a dictionary with some key-value pairs and find the sum of keys in the dictionary.
Conclusion
In this article, we covered common operations that can be applied to tuples and dictionaries in Python. Practice these operations to strengthen your understanding. Join the community to engage with fellow learners and expand your Python knowledge further!
Common Operations
There are some functions which can be applied on all collections. Here we will see details related to tuple
and dict
using Python as programming language.
-
in
- check if element exists in thetuple
-
in
can also be used ondict
. It checks if the key exists in thedict
. -
len
- to get the number of elements. -
sorted
- to sort the data (original collection will be untouched). Typically, we assign the result of sorting to a new collection. -
sum
,min
,max
, etc - arithmetic operations. In case ofdict
, the operations will be performed on key. -
There can be more such functions.
t = (1, 2, 3, 4) # tuple
1 in t
5 in t
len(t)
sorted(t, reverse=True)
sum(t)
d = {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’} # dict
1 in d
5 in d
‘a’ in d
len(d)
sorted(d) # only sorts the keys
sum(d) # applies only on keys