Python tuple contains tuple

How to check if a tuple contains an element in Python

In this post, we will learn how to check if a Python tuple contains an element. There are different ways to check that. We can either iterate through its items or we can use an if-else block to do that.

In this post, I will show you how to check if a tuple contains an item in three different ways.

Let’s implement it with a loop. We will iterate through each item of the tuple one by one and compare it with the given value. If any value in the tuple is equal to the given value, it will return True . Else, it will return False .

Below is the complete program:

def contains(tuple, given_char): for ch in tuple: if ch == given_char: return True return False given_tuple = ("a", "b", "c", "d", "e", "f", "g", "h") print(f"Given tuple: given_tuple>") char = input("Enter a character to find: ") if contains(given_tuple, char): print("It is in the tuple") else: print("It is not in the tuple")
  • The contains method is used to check if a character is in the tuple given_tuple or not.
    • This method returns one boolean value. Based on the return value of this method, it prints a message to the user.

    If you run this program, it will print outputs as below:

    tuple: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') Enter a character to find: i It is not in the tuple Given tuple: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') Enter a character to find: e It is in the tuple

    We can also use this approach with a tuple of objects. e.g.:

    def contains(tuple, item): for i in tuple: if i == item: return True return False given_tuple = ("id": 1, "name": "Alex">, "id": 2, "name": "Bob">) print(f"Given tuple: given_tuple>") item = "id": 4, "name": "Bob"> if contains(given_tuple, item): print(f"item> is in the tuple") else: print(f"item> is not in the tuple")
    tuple: ('id': 1, 'name': 'Alex'>, 'id': 2, 'name': 'Bob'>) 'id': 4, 'name': 'Bob'> is not in the tuple

    Instead of comparing with the == operator, you can also add any other comparison function to compare two items.

    We can also quickly check if an element is in a tuple or not by using one if..not check. Let me change the above program to use if..not :

    def contains(tuple, given_char): if given_char in tuple: return True return False given_tuple = ("a", "b", "c", "d", "e", "f", "g", "h") print(f"Given tuple: given_tuple>") char = input("Enter a character to find: ") if contains(given_tuple, char): print("It is in the tuple") else: print("It is not in the tuple")

    It will print similar output:

    tuple: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') Enter a character to find: g It is in the tuple

    Python check if a tuple contains an element

    As you can see here, we can do it easily with only one line. No need to iterate over the tuple.

    Источник

    Python Tuple

    You can create a tuple by placing a comma-separated sequence of items in parentheses () .

    # A tuple of integers T = (1, 2, 3) # A tuple of strings T = ('red', 'green', 'blue')

    The items of a tuple don’t have to be the same type. The following tuple contains an integer, a string, a float, and a boolean.

    # A tuple with mixed datatypes T = (1, 'abc', 1.23, True)

    A tuple containing zero items is called an empty tuple and you can create one with empty
    brackets ()

    Syntactically, a tuple is just a comma-separated list of values.

    # A tuple without parentheses T = 1, 'abc', 1.23, True

    You don’t need the parentheses to create a tuple. It’s the trailing commas that really define a tuple. But using them doesn’t hurt; also they help make the tuple more visible.

    Singleton Tuple

    If you have only one value in a tuple, you can indicate this by including a trailing comma , just before the closing parentheses.

    Otherwise, Python will think you’ve just typed a value inside regular parentheses.

    # Not a tuple T = (4) print(type(T)) # Prints 

    The tuple() Constructor

    You can convert other data types to tuple using Python’s tuple() constructor.

    # Convert a list to a tuple T = tuple([1, 2, 3]) print(T) # Prints (1, 2, 3)
    # Convert a string to a tuple T = tuple('abc') print(T) # Prints ('a', 'b', 'c')

    Nested Tuples

    A tuple can contain sub-tuple, which in turn can contain sub-tuples themselves, and so on. This is known as nested tuple. You can use them to arrange data into hierarchical structures.

    Tuple Packing & Unpacking

    Tuple Packing

    When a tuple is created, the items in the tuple are packed together into the object.

    T = ('red', 'green', 'blue', 'cyan') print(T) # Prints ('red', 'green', 'blue', 'cyan')

    In above example, the values ‘red’, ‘green’, ‘blue’ and ‘cyan’ are packed together in a tuple.

    Tuple Packing

    Tuple Unpacking

    When a packed tuple is assigned to a new tuple, the individual items are unpacked (assigned to the items of a new tuple).

    T = ('red', 'green', 'blue', 'cyan') (a, b, c, d) = T print(a) # Prints red print(b) # Prints green print(c) # Prints blue print(d) # Prints cyan

    In above example, the tuple T is unpacked into a, b, c and d variables.

    Tuple Unpacking

    When unpacking, the number of variables on the left must match the number of items in the tuple.

    # Common errors in tuple unpacking T = ('red', 'green', 'blue', 'cyan') (a, b) = T # Triggers ValueError: too many values to unpack T = ('red', 'green', 'blue') (a, b, c, d) = T # Triggers ValueError: not enough values to unpack (expected 4, got 3)

    Usage

    Tuple unpacking comes handy when you want to swap values of two variables without using a temporary variable.

    # Swap values of 'a' and 'b' a = 1 b = 99 a, b = b, a print(a) # Prints 99 print(b) # Prints 1

    While unpacking a tuple, the right side can be any kind of sequence (tuple, string or list).

    # Split an email address into a user name and a domain addr = '[email protected]' user, domain = addr.split('@') print(user) # Prints bob print(domain) # Prints python.org

    Access Tuple Items

    You can access individual items in a tuple using an index in square brackets. Note that tuple indexing starts from 0.

    The indices for the elements in a tuple are illustrated as below:

    Python Tuple Indexing

    T = ('red', 'green', 'blue', 'yellow', 'black') print(T[0]) # Prints red print(T[2]) # Prints blue

    You can access a tuple by negative indexing as well. Negative indexes count backward from the end of the tuple. So, T[-1] refers to the last item, T[-2] is the second-last, and so on.

    T = ('red', 'green', 'blue', 'yellow', 'black') print(T[-1]) # Prints black print(T[-2]) # Prints yellow

    Tuple Slicing

    To access a range of items in a tuple, you need to slice a tuple using a slicing operator. Tuple slicing is similar to list slicing.

    T = ('a', 'b', 'c', 'd', 'e', 'f') print(T[2:5]) # Prints ('c', 'd', 'e') print(T[0:2]) # Prints ('a', 'b') print(T[3:-1]) # Prints ('d', 'e')

    Change Tuple Items

    Tuples are immutable (unchangeable). Once a tuple is created, it cannot be modified.

    T = ('red', 'green', 'blue') T[0] = 'black' # Triggers TypeError: 'tuple' object does not support item assignment

    The tuple immutability is applicable only to the top level of the tuple itself, not to its contents. For example, a list inside a tuple can be changed as usual.

    T = (1, [2, 3], 4) T[1][0] = 'xx' print(T) # Prints (1, ['xx', 3], 4)

    Delete a Tuple

    Tuples cannot be modified, so obviously you cannot delete any item from it. However, you can delete the tuple completely with del keyword.

    Tuple Concatenation & Repetition

    Tuples can be joined using the concatenation operator + or Replication operator *

    # Concatenate T = ('red', 'green', 'blue') + (1, 2, 3) print(T) # Prints ('red', 'green', 'blue', 1, 2, 3) # Replicate T = ('red',) * 3 print(T) # Prints ('red', 'red', 'red')

    Find Tuple Length

    To find how many items a tuple has, use len() method.

    T = ('red', 'green', 'blue') print(len(T)) # Prints 3

    Check if item exists in a tuple

    To determine whether a value is or isn’t in a tuple, you can use in and not in operators with if statement.

    # Check for presence T = ('red', 'green', 'blue') if 'red' in T: print('yes') # Check for absence T = ('red', 'green', 'blue') if 'yellow' not in T: print('yes')

    Iterate through a tuple

    To iterate over the items of a tuple, use a simple for loop.

    T = ('red', 'green', 'blue') for item in T: print(item) # Prints red green blue

    Tuple Sorting

    There are two methods to sort a tuple.

    Method 1: Use the built-in sorted() method that accepts any sequence object.

    T = ('cc', 'aa', 'dd', 'bb') print(tuple(sorted(T))) # Prints ('aa', 'bb', 'cc', 'dd')

    Method 2: Convert a tuple to a mutable object like list (using list constructor), gain access to a sorting method call (sort()) and convert it back to tuple.

    T = ('cc', 'aa', 'dd', 'bb') tmp = list(T) # convert tuple to list tmp.sort() # sort list T = tuple(tmp) # convert list to tuple print(T) # Prints ('aa', 'bb', 'cc', 'dd')

    Python Tuple Methods

    Python has a set of built-in methods that you can call on tuple objects.

    Python tuple Methods

    Method Description
    count() Returns the count of specified item in the tuple
    index() Returns the index of first instance of the specified item

    Built-in Functions with Tuple

    Python also has a set of built-in functions that you can use with tuple objects.

    Python Built-in Functions with Tuple

    Method Description
    all() Returns True if all tuple items are true
    any() Returns True if any tuple item is true
    enumerate() Takes a tuple and returns an enumerate object
    len() Returns the number of items in the tuple
    max() Returns the largest item of the tuple
    min() Returns the smallest item of the tuple
    sorted() Returns a sorted tuple
    sum() Sums items of the tuple
    tuple() Converts an iterable (list, string, set etc.) to a tuple

    Источник

Читайте также:  You should add extension mcrypt so to php ini
Оцените статью