Python Tuples, Dictionary and Sets
Python Tuples, Dictionary and Sets
Sets
Tuples
• A tuple in Python is similar to a list.
• The difference between the two is that
– we cannot change the elements of a tuple once it
is assigned
– whereas we can change the elements of a list.
Creating a Tuple
• A tuple is created by placing all the items (elements)
inside parentheses (), separated by commas.
• A tuple can have any number of items and they may
be of different types (integer, float, list, string, etc.).
Access Tuple Elements
• Indexing
– We can use the index operator [] to access an item in a
tuple, where the index starts from 0.
• Negative Indexing
– Python allows negative indexing for its sequences.
– The index of -1 refers to the last item, -2 to the second
last item and so on.
• Slicing
– We can access a range of items in a tuple by using the
slicing operator colon :.
Access Tuple Elements (Examples)
Indexing
Negative Indexing
Slicing
Deleting a Tuple
• We cannot change the elements in a tuple.
• It means that we cannot delete or remove
items from a tuple.
• Deleting a tuple entirely, however, is possible
using the keyword del.
Tuple Methods
• Methods that add items or remove items are
not available with tuple.
• Only the following two methods are available.
Python Dictionary
• Python dictionary is an unordered collection
of items. Each item of a dictionary has a
key/value pair.