StudyLover
  • Home
  • Study Zone
  • Profiles
  • Typing Tutor
  • Contact us
  • Sign in
StudyLover Tuple
Download
  1. Python
  2. Pyhton MCA (Machine Learning using Python)
  3. Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP
List : Sets
Unit 3: Getting Started with Python: A Guide to Syntax, Data Structures, and OOP

A tuple in Python is a fundamental data structure used to store an ordered collection of items. It is very similar to a list, but with one critical difference: tuples are immutable. This means that once a tuple is created, its contents cannot be changed, added to, or removed. Tuples are created by placing items inside parentheses (), separated by commas.

Key Characteristics of Tuples

  • Ordered: The items in a tuple have a defined order, and that order will not change.

  • Immutable: This is the key feature. You cannot change a tuple after it has been created. This provides a form of data integrity, ensuring that the data remains constant.

  • Allows Duplicates: Tuples can contain multiple items with the same value.

  • Efficient: Because they are immutable, tuples are slightly more memory-efficient and faster to process than lists.

Python

# A tuple of numbers

numbers = (1, 2, 3, 4, 5)

 

# A tuple with mixed data types and duplicates

mixed_tuple = ("hello", 3.14, 1, "hello")

 

print(f"A simple tuple: {numbers}")

print(f"A mixed-type tuple: {mixed_tuple}")


Operations with Operators

Concatenation (+)

Combines two tuples to create a new, single tuple.

Python

tuple1 = (1, 2, 3)

tuple2 = ('a', 'b', 'c')

combined_tuple = tuple1 + tuple2

print(f"Concatenation (+): {combined_tuple}")

# Output: (1, 2, 3, 'a', 'b', 'c')

Repetition (*)

Creates a new tuple by repeating the original tuple's elements a specified number of times.

Python

repeated_tuple = ('x', 'y') * 3

print(f"Repetition (*): {repeated_tuple}")

# Output: ('x', 'y', 'x', 'y', 'x', 'y')

Indexing ([])

Accesses a single item at a specific position (index). Python uses zero-based indexing.

Python

coordinates = (10, 20, 30)

print(f"First item (index 0): {coordinates[0]}")      # Output: 10

print(f"Last item (index -1): {coordinates[-1]}")     # Output: 30

Slicing ([:])

Extracts a portion of the tuple, creating a new tuple.

Python

numbers = (10, 20, 30, 40, 50, 60)

print(f"Slice from index 2 to 4: {numbers[2:5]}") # Output: (30, 40, 50)

Membership Testing (in, not in)

Checks if an item exists within a tuple, returning True or False.

Python

fruits = ("apple", "banana", "cherry")

print(f"Is 'banana' in the tuple? {'banana' in fruits}")       # Output: True

print(f"Is 'mango' not in the tuple? {'mango' not in fruits}") # Output: True


Built-in Functions for Tuples

len()

Returns the number of items in a tuple.

Python

numbers = (10, 20, 30, 40)

print(f"Length of the tuple: {len(numbers)}") # Output: 4

sum(), min(), max()

Returns the sum, minimum, or maximum item in a tuple. These only work if all items are numbers.

Python

numbers = (5, 2, 8, 1, 9)

print(f"Sum of numbers: {sum(numbers)}")   # Output: 25

print(f"Min of numbers: {min(numbers)}")   # Output: 1

print(f"Max of numbers: {max(numbers)}")   # Output: 9

sorted()

Returns a new, sorted list from the items in the tuple. Note that it does not return a tuple.

Python

unsorted_tuple = (3, 1, 4, 1, 5, 9)

sorted_list_from_tuple = sorted(unsorted_tuple)

print(f"Original tuple: {unsorted_tuple}")

print(f"New sorted list: {sorted_list_from_tuple}")


Tuple Methods

Because tuples are immutable, they have very few methods. They lack methods like .append() or .remove() that would modify the tuple.

.count(item)

Returns the number of times a specified item appears in the tuple.

Python

my_tuple = ('a', 'b', 'c', 'a', 'a')

print(f"Count of 'a': {my_tuple.count('a')}") # Output: 3

.index(item)

Returns the index of the first occurrence of a specified item. It will raise an error if the item is not found.

Python

my_tuple = ('a', 'b', 'c', 'a')

print(f"Index of 'b': {my_tuple.index('b')}") # Output: 1


Special Cases and Features

Creating a Single-Item Tuple

To create a tuple with only one item, you must include a trailing comma. Without it, Python will just see the item's data type.

Python

not_a_tuple = (5)

is_a_tuple = (5,)

print(f"Type of (5): {type(not_a_tuple)}")   # Output: <class 'int'>

print(f"Type of (5,): {type(is_a_tuple)}") # Output: <class 'tuple'>

Tuple Unpacking

This is a powerful feature where you can assign the items of a tuple to multiple variables in a single line.

Python

# Assigning items from a tuple to variables

point = (10, 20)

x, y = point

print(f"Unpacked values: x={x}, y={y}")

 

# Swapping variables easily

a = 5

b = 10

a, b = b, a # Under the hood, this uses a tuple

print(f"Swapped values: a={a}, b={b}")

 

List Sets
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website