Tuples and Sets in Python

Index

Definition and Creating Tuples

A tuple is a finite ordered list of values of possibly different types which is used to bundle related values together without having to create a specific type to hold them.

Tuples are immutable. Once a tuple is created, you cannot change its values(Also the Difference between lists and tuples).

The tuples can be converted to dictionaries by passing the tuple name to the dict() function. This is achieved by nesting tuples within tuples, wherein each nested tuple item should have two items in it. The first item becomes the key and second item as its value when the tuple gets converted to a dictionary.

Tuples can be used as key:value pairs to build dictionaries.

A tuple is defined by putting a comma-separated list of values inside parentheses ( ).

Each value inside a tuple is called an item.

The syntax for creating tuples is,

tuple_name = (item_1, item_2, item_3, ………….., item_n)

For example

**>>> internet = ("cern", "timbernerslee", "www", 1980)
>>> internet
	('cern', 'timbernerslee,' 'www', 1980)
>>> type(internet)
	<class 'tuple'>
>>> f1 = "ferrari", "redbull", "mercedes", "williams", "renault"
>> f1
	('ferrari', 'redbull', 'mercedes', 'williams', 'renault')
>>> type(f1)
	<class 'tuple'>**

You can create an empty tuple without any values. The syntax is,

tuple_name = ()

Operations on Tuples

  • you can use the + operator to concatenate tuples together and the * operator to repeat a sequence of tuple items For example,
    • >>> tuple_1 = (2, 0, 1, 4)
    • >>> tuple_2 = (2, 0, 1, 9)
    • >>> tuple_1 + tuple_2 (2, 0, 1, 4, 2, 0, 1, 9)
    • >>> tuple_1 * 3 (2, 0, 1, 4, 2, 0, 1, 4, 2, 0, 1, 4)
    • >>> tuple_1 == tuple_2 False
  • You can check for the presence of an item in a tuple using in and not in membership operators. It returns a Boolean True or False. For example,
    • >>> tuple_items = (1, 9, 8, 8)
    • >>> 1 in tuple_items True
    • >>> 25 in tuple_items False
  • Comparison operators like <, <=, >, >=, == and != are used to compare tuples. For example,
    • >>> tuple_1 = (9, 8, 7)
    • >>> tuple_2 = (9, 1, 1)
    • >>> tuple_1 > tuple_2 True
    • >>> tuple_1 != tuple_2 True

The tuple() Function

The built-in tuple() function is used to create a tuple. The syntax for the tuple() function is,

tuple([sequence])

where the sequence can be a number, string or tuple itself. If the optional sequence is not specified, then an empty tuple is created.

The string variable is converted to a tuple using the tuple() function. Not only strings, but even list variables can be converted to tuples. If you try to concatenate either a string or a list with tuples, then it results in an error. You have to convert strings and lists to tuples using tuple() function before concatenating with tuple types and. Nesting of tuples is allowed in Python. An output of a tuple operation is always enclosed in parentheses so that nested tuples are interpreted correctly – . Each individual character in a string is separated by a comma when a string is converted to a tuple .

>>> norse = "vikings"
>>> string_to_tuple = tuple(norse)
>>> string_to_tuple
	('v', 'i', 'k', 'i', 'n', 'g', 's')
>>> zeus = ["g", "o", "d", "o", "f", "s", "k", "y"]
>>> list_to_tuple = tuple(zeus)
>>> list_to_tuple
	('g', 'o', 'd', 'o', 'f', 's', 'k', 'y')
>>> string_to_tuple + "scandinavia"
	Traceback (most recent call last):
	 File "<stdin>", line 1, in <module>
	TypeError: can only concatenate tuple (not "str") to tuple
>>> string_to_tuple + tuple("scandinavia")
	('v', 'i', 'k', 'i', 'n', 'g', 's', 's', 'c', 'a', 'n', 'd', 'i', 'n', 'a', 'v', 'i', 'a')
>>> list_to_tuple + ["g", "r", "e", "e", "k"]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> list_to_tuple + tuple(["g", "r", "e", "e", "k"])
	('g', 'o', 'd', 'o', 'f', 's', 'k', 'y', 'g', 'r', 'e', 'e', 'k')
>>> letters = ("a", "b", "c")
>>> numbers = (1, 2, 3)
>>> nested_tuples = (letters, numbers)
>>> nested_tuples
	(('a', 'b', 'c'), (1, 2, 3))
>>> tuple("wolverine")
	('w', 'o', 'l', 'v', 'e', 'r', 'i', 'n', 'e')

Built-in Functions on Tuples

There are many built-in functions for which a tuple can be passed as an argument.

Built-In FunctionsDescription
len()The len() function returns the numbers of items in a tuple.
sum()The sum() function returns the sum of numbers in the tuple.
sorted()The sorted() function returns a sorted copy of the tuple as a list while leaving the original tuple untouched.

For example,

>>> years = (1987, 1985, 1981, 1996)
>>> len(years)
	4
>>> sum(years)
	7949
>>> sorted_years = sorted(years)
>>> sorted_years
	[1981, 1985, 1987, 1996]

Tuple Methods

Various tubple methods

Tuple MethodsSyntaxDescription
count()tuple_name.count(item)The count() method counts the number of times the item has occurred in the tuple and returns it.
index()tuple_name.index(item)The index() method searches for the given item from the start of the tuple and returns its index. If the value appears more than once, you will get the index of the first one. If the item is not present in the tuple, then ValueError is thrown by this method.

For example,

>>> channels = ("ngc", "discovery", "animal_planet", "history", "ngc")
>>> channels.count("ngc")
	2
>>> channels.index("history")
	3

Creating Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate items. Primary uses of sets include membership testing and eliminating duplicate entries. Sets also support mathematical operations, such as union, intersection, difference, and symmetric difference.

A set is a collection of unique items. Duplicate items are removed from the set basket. You can test for the presence of an item in a set using in and not in membership operators

Sets are mutable. Indexing is not possible in sets, since set items are unordered. You cannot access or change an item of the set using indexing or slicing.

Curly braces { } or the set() function can be used to create sets with a comma-separated list of items inside curly brackets { }.

Note: to create an empty set you have to use set() and not { } as the latter creates an empty dictionary.

For example,

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
	{'pear', 'orange', 'banana', 'apple'}
>>> 'orange' in basket
	True
>>> 'crabgrass' in basket
	False
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
	{'d', 'a', 'b', 'r', 'c'}
>>> b
		{'m', 'l', 'c', 'z', 'a'}
>>> a – b
	{'b', 'r', 'd'}
>>> a | b
	{'l', 'm', 'z', 'd', 'a', 'b', 'r', 'c'}
>>> a & b
	{'a', 'c'}
>>> a ^ b
	{'l', 'd', 'm', 'b', 'r', 'z'}
>>> len(basket)
	4
>>> sorted(basket)
	['apple', 'banana', 'orange', 'pear']

Operations on Sets

Traversing of Sets

You can iterate through each item in a set using a for loop.

warships = {"u.s.s._arizona", "hms_beagle", "ins_airavat", "ins_hetz"}
def main():
for each_ship in warships:
print(f"{each_ship} is a Warship")
if __name__ == "__main__":
main()

Set Methods

Various methods associated with set are displayed

Set MethodsSyntaxDescription
add()set_name.add(item)The add() method adds an item to the set set_name.
clear()set_name.clear()The clear() method removes all the items from the set set_name.
difference()set_name.difference(*others)The difference() method returns a new set with items in the set set_name that are not in the others sets.
discard()set_name.discard(item)The discard() method removes an item from the set set_name if it is present.
intersection()set_name.intersection(*others)The intersection() method returns a new set with items common to the set set_name and all others sets.
isdisjoint()set_name.isdisjoint(other)The isdisjoint() method returns True if the set set_name has no items in common with other set. Sets are disjoint if and only if their intersection is the empty set.
issubset()set_name.issubset(other)The issubset() method returns True if every item in the set set_name is in other set.
issuperset()set_name.issuperset(other)The issuperset() method returns True if every element in other set is in the set set_name.
pop()set_name.pop()The method pop() removes and returns an arbitrary item from the set set_name. It raises KeyError if the set is empty.
remove()set_name.remove(item)The method remove() removes an item from the set set_name. It raises KeyError if the item is not contained in the set.
symmetric_difference()set_name.symmetric_difference(other)The method symmetric_difference() returns a new set with items in either the set or other but not both.
union()set_name.union(*others)The method union() returns a new set with items from the set set_name and all others sets.
update()set_name.update(*others)Update the set set_name by adding items from all others sets.

For example,

>>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}
>>> american_flowers = {"roses", "tulips", "lilies", "daisies"}
>>> american_flowers.add("orchids")
>>> american_flowers.difference(european_flowers)
	{'lilies', 'orchids', 'daisies'}
>>> american_flowers.intersection(european_flowers)
	{'roses', 'tulips'}
>>> american_flowers.isdisjoint(european_flowers)
	False
>>> american_flowers.issuperset(european_flowers)
	False
>>> american_flowers.issubset(european_flowers)
	False
>>> american_flowers.symmetric_difference(european_flowers)
	{'lilies', 'orchids', 'daisies', 'goldcrest', 'sunflowers', 'lavender'}
>>> american_flowers.union(european_flowers)
	{'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}
>>> american_flowers.update(european_flowers)
>>> american_flowers
	{'lilies', 'tulips', 'orchids', 'sunflowers', 'lavender', 'roses', 'goldcrest', 'daisies'}
>>> american_flowers.discard("roses")
>>> american_flowers
	{'lilies', 'tulips', 'orchids', 'daisies'}
>>> european_flowers.pop()
	'tulips'
>>> american_flowers.clear()
>>> american_flowers
	set()
Shelton Coutinho
Shelton Coutinho
Articles: 13

Leave a Reply

Your email address will not be published. Required fields are marked *