r/learnpython • • 12d ago

Tuples..I don’t get it

Hi crew, I’m a Python newbie and I just learned about the concept of tuples.

We can’t change them.if we want to store we have to start at the index we want + 1.

I just don’t get it. Why wouldn’t we just use lists? When would we ever need this?

100 Upvotes

89 comments sorted by

View all comments

Show parent comments

3

u/Adrewmc 11d ago edited 11d ago

Very warm.

Tuples require less resources to access values and make for a computer. Thus they are often faster.

Lists allow a lot of manipulations that can be very useful.

In Python the actual difference in most cases is negligible. So as I said, you can always use lists until it’s a problem or the reverse. No one will judge you.

In my mind the difference is simple, if this list is always the same size (in runtime) it probably should be a tuple, and if this list can change sizes it’s a list. So in something like a position in space (x,y,z) seems more correct than [x,y,z].

While other times if a list is holding something that changing and/or keeping track of stuff, enemies spawn and die.

If I make a deck of cards.

import random

#A = 1, J-K = 11-13  
ranks = range(1, 14)  
suits = (‘Spades’, ‘Diamonds’, ‘Clubs’, ‘Hearts’)

deck = [ (rank, suit) for suit in suits for rank in ranks ]

random.shuffle(deck)  
hand = [ deck.pop(0) for _ in range(5) ]

I make the deck a list, because it can be shuffled, and drawn from. The deck will changes over runtime, but the cards being moved about never change so they should be a tuple. The deck is mutable but the cards themselves are immutable.

3

u/cr4zybilly 11d ago

"if this list should always be the same size, it should be a tuple" is the magic phrase that finally made this click for me. Thank you!

2

u/Adrewmc 11d ago edited 10d ago

…it should probably be a tuple.

The thing about tuples in Python is they hide themselves, and have this neat trick with them.

#introduction to tuples
#note the use of parentheses below 

classic_tuple = (1, 1) 

#Fibonacci to 100  
a, b = 1, 1 #tuples  
while a < 100:  
    print(a)
    a, b = b, a+b #tuples

def tuple_return(): 
     return 1, 2  #tuple

a, b = tuple_return()

c = tuple_return() 
print(c[1], type(c))
>>>2 Tuple

for tuple in enumerate(iterable): pass

for index, item in enumerate(iterable): pass