Core Python / Tuples

Core Python / Tuples#

  1. What are the differences between lists and tuples?

    Lists and tuples both contain heterogenous data values in a particular order and those elements(values) are accessed in the same manner []. The primary difference is that tuples are immutable -
    we cannot change the elements inside of the tuple.

  2. Explain how multiple values can be returned from a function in Python.

    Mulitple values are returned by utilizing a tuple. The return values can then be assigned to a tuple or unpacked into multiple variables.

  3. How are tuples created? Provide examples.

    Tuples are created by separating expressions by a comma. While optional, parenthesis are preferred to make it easier for readers to see that a tuple is being created. The built-in function, tuple() can also be used - a sequence needs to be provided to the function.

    t = 1,"test", 4.0
    w = ("test",5, 3.14)
    x = tuple("hello")  # x contains 5 elements
    print(x)
    x = tuple(["hello", "world"]) # contains two elements
    print(x)
    
  4. Explain how sequences work across strings, lists, and tuples.

    Sequences allow us to treat strings, lists, and tuples in a similar manner and can apply slicing to access specific parts of those items.

  5. How do you access elements in a tuple? Provide examples.

    We can directly access a member using the [] operator. We can also apply slicing.

    >>> phrase = ("it","was","the","best","of","times")
    >>> print(phrase)
    ('it', 'was', 'the', 'best', 'of', 'times')
    >>> type(phrase)
    <class 'tuple'>
    >>> phrase[-1]
    'times'
    >>> phrase[5]
    'times' 
    >>> phrase[0]
    'it'
    >>> phrase[-2:]
    ('of', 'times')
    >>> phrase[4:]
    ('of', 'times')
    
  6. Can a tuple contain mutable objects like lists? Explain.

    Yes. However, the tuple cannot be used as a key for a dictionary entry. The entries in that list can be altered.