0% found this document useful (0 votes)
10 views

Tuples in Python

Uploaded by

vedaiitcse05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Tuples in Python

Uploaded by

vedaiitcse05
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Yogesh Tyagi

@ytyagi782

Tuples in
Python
lete Guide
A Comp
Yogesh Tyagi
@ytyagi782

Tuples in Python: A
Complete Guide

Learn how to use Python tuples effectively to


store and manage immutable collections of
data in your programs.
Yogesh Tyagi
@ytyagi782

What is a Tuple in
Python?
A tuple is a collection data type in Python that is:

Ordered: Items maintain their insertion order.

Immutable: Once created, elements in a tuple cannot be


modified.

Heterogeneous: Can store items of different data types.

Example

Key
Features Tuples are faster than Often used for fixed data
like coordinates or
lists due to immutability. configuration settings.
Yogesh Tyagi
@ytyagi782

Creating Tuples

Basic Tuple
Creation

To create a tuple with one element, include a trailing


comma.
Creating a
Single-
Element Tuple

Using the
tuple()
Constructor

Empty Tuple
Yogesh Tyagi
@ytyagi782

Accessing Tuple
Elements
You can access tuple elements using indexing.

Indexing Negative indexing


starts at 0. starts at -1.

Examples

Note: Attempting to modify a tuple


element will raise a TypeError.
Yogesh Tyagi
@ytyagi782

Slicing Tuples

Tuples support slicing to access multiple elements.

Syntax

Examples

Omitting start Omitting end


Key Notes begins slicing slices to the
from the start. last element.
Yogesh Tyagi
@ytyagi782

Iterating Through
Tuples

Tuples are iterable, allowing you to use loops to


access their elements.

Example with for loop:

Output:
Yogesh Tyagi
@ytyagi782

Tuple Packing and


Unpacking

Assign multiple values to a single tuple.

Tuple
Packing

Assign
Tuple multiple
values to a
Unpacking single tuple.

Use Case Swapping


values.
Yogesh Tyagi
@ytyagi782

Common Errors with


Tuples

Trying to modify a tuple.

TypeError

Accessing out-of-range indices.

IndexError

Using index() with a non-existing value.

ValueError
Yogesh Tyagi
@ytyagi782

Wrap-Up

"Tuples: Immutable and Powerful Collections in Python"

Tuples are an essential data structure in Python, offering


immutability, speed, and versatility. Use tuples for fixed
collections of data, dictionary keys, and lightweight
alternatives to lists when modifications aren't needed.
Practice working with tuples to unlock their full potential!
Yogesh Tyagi
@ytyagi782

Follow for More

You might also like