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 (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (117) C (77) C# (12) C++ (82) Course (62) Coursera (179) coursewra (1) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (748) Python Coding Challenge (221) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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