Tuesday, 23 April 2024

Taming Data with Tuples



Creating Tuples:

You can create a tuple by enclosing a sequence of elements within parentheses ().


tuple1 = (1, 2, 3)

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

mixed_tuple = (1, 'hello', 3.14)


#clcoding.com 

Accessing Elements:

You can access elements of a tuple using indexing, just like with lists.


tuple1 = (1, 2, 3)

print(tuple1[0])  

print(tuple1[1])  


#clcoding.com 

1

2

Iterating over Tuples:

You can iterate over the elements of a tuple using a loop.

tuple1 = ('apple', 'banana', 'cherry')
for fruit in tuple1:
    print(fruit)
    
#clcoding.com
apple
banana
cherry

Tuple Methods:

Tuples have only two built-in methods: count() and index().

tuple1 = (1, 2, 2, 3, 4, 2)
print(tuple1.count(2))  # Output: 3
print(tuple1.index(3))  # Output: 3

#clcoding.com
3
3


Immutable Nature:

Once a tuple is created, you cannot modify its elements.


tuple1 = (1, 2, 3)

# This will raise an error

tuple1[0] = 4


#clcoding.com

Tuple Unpacking:

You can unpack a tuple into individual variables.


tuple1 = ('apple', 'banana', 'cherry')

a, b, c = tuple1

print(a)  

print(b)  

print(c)  


#clcoding.com

apple

banana

cherry


Returning Multiple Values from Functions:

Functions in Python can return tuples, allowing you to return multiple values.


def get_coordinates():

    x = 10

    y = 20

    return x, y


x_coord, y_coord = get_coordinates()

print("x coordinate:", x_coord)  

print("y coordinate:", y_coord)  


#clcoding.com

x coordinate: 10

y coordinate: 20

Iterating over Tuples:

You can iterate over the elements of a tuple using a loop.


tuple1 = ('apple', 'banana', 'cherry')

for fruit in tuple1:

    print(fruit)

    

#clcoding.com

apple

banana

cherry

0 Comments:

Post a Comment

Popular Posts

Categories

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses