Uday's Notes - Python Why Tuple. Why not List.

Why Tuple. Why not List

#python #list #tuple

Tuple -

immutable. Faster. Stored in one block of memory.

atuple = ("ding", "dong", 69)

Weird Tuples -

thisisatuple = 9, # comma is all you need for a tuple lol

List -

mutable. Slightly slower (obviously has a greater impact in larger programs -- need to check). Stored in two blocks of memory.

alist = ["ping", "pong", 420]

Why?

  1. SQL Libraries in Python return tuples when you use fetchone() or fetchall()

  2. You store homogeneous data in lists and heterogeneous data in tuples. Example -

    alist = ["Uday", "Ajay", "Sukhjeet", "Shubh"] #only names here
    atuple = ("Uday", 18, "First Year") #name, age, year here
    
    
    

## Unpacking Tuples, Lists

```python
(name, age, year) = atuple
print(name) # cprints Uday
print(age) # prints 18
print(Year) # prints First Year

Nested Tuples and Lists

You can nest tuples and lists inside each other.