Tuples Flashcards

1
Q

What is a Tuple?

A
  • A tuple looks just like a list
  • Tuples are immutable
  • Use parentheses instead of square brackets dimensions = (200, 50) .
  • Once you define a tuple, you can access individual elements by using each item’s index, just as you would for a list.
    ~~~
    dimensions = (200, 50)
    print(dimensions[0])
    print(dimensions[1])
    ~~~
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Looping Through All Values in a Tuple

A
dimensions = (200, 50)
for dimension in dimensions:
    print(dimension)
		
200
50
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Writing Over a Tuple

A
  • Although you can’t modify a tuple, you can assign a new value to a variable that represents a tuple.
  • The first four lines define the original tuple and print the initial dimensions. We then associate a new tuple with the variable dimensions, and print the new values. Python doesn’t raise any errors this time, because reassigning a variable is valid:
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

Original dimensions:
200
50

dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)

Modified dimensions:
400
100
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

When to use Tuples?

A
  • When compared with lists, tuples are simple data structures.
    * Use them when you want to store a set of values that should not be changed throughout the life of a program.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly