En ordnad samling element som vart och ett kan identifieras med ett nummer, ett s.k index.
🤔 Känns bekant?
numbers = (1, 2 , 3, 4)
1. Parenteser istället för hakparenteser []
2. Oföränderliga (immutable!)
Kan inte ändras!
x = (1,2,3)
x[0] = "change me!"
# TypeError: 'tuple' object does not support item assignment
first_tuple = (1, 2, 3, 3, 3)
first_tuple[1] // 2
first_tuple[2] // 3
first_tuple[-1] // 3
second_tuple = tuple(5, 1, 2)
second_tuple[0] # 5
second_tuple[-1] # 2
Skapa en tuple med () eller funktionen tuple
x = (1,2,3,3,3)
x.count(1) # 1
x.count(3) # 3
Har bara två metoder, count() och index()
t = (1,2,3,3,3)
t.index(1) # 0
t.index(5) # ValueError: tuple.index(x): x not in tuple
t.index(3) # 2 - only the first matching index is returned
movie = ("Tarantino", 2012, 8.4, "Waltz & DiCaprio")
(director, year, imdb_rating) = movie
"Packa in"
"Packa upp"
med tuples
Hanteringen av tuples dem kräver mindre resurser än vad listor gör. Körningstid, lagringsutrymme.
Din kod kan bli "säkrare" när data ska hållas oföränderligt.