1,234
edits
Changes
→PART 1 - Tuples
::*'''Data protection''' (eg. values are are NOT allowed to change so you won't modify them accidentally)
::*Tuples can be used as '''keys in data dictionaries''' (which are NOT allowed to change)
::*Tuples allow for '''faster access''' than lists
:'''Perform the Following Steps:'''
:#Launch your Centos VM, open a shell terminal (as a regular user) and start a new ipython3 session:<source>ipython3</source>Let's create two tuplesin a temporary Python file, so we can learn how to use them and learn how they differ from lists.<br><br>Note: '''tuples are defined by using parenthesis ( )''' as opposed to '''lists which are defined by using square brackets [ ]'''<br><br>:#Issue the following:<source lang="python">
t1 = ('Prime', 'Ix', 'Secundus', 'Caladan')
t2 = (1, 2, 3, 4, 5, 6)
</source>
:#Values from a tuple can be retrieved in the same way as a list. For example, issue the following:<source lang="python">print(t1[0])print(t2[2:4])
</source>
:#You can also check to see whether a value exists inside a tuple or not. To demonstrate, issue the followingtry:<source lang="python">print('Ix' in t1)print('Geidi' in t1)</source>Let's now see how a tuple differs from a list. We will now create a list and note the difference between them.<br><br>:#Issue the following to create a list:<source lang="python">
list2 = [ 'uli101', 'ops235', 'ops335', 'ops435', 'ops535', 'ops635' ]
</source>
:#See if you can change the value of your list by issuing the following:<source lang="python">
list2[0]= 'ica100'
print(list2[0])
print(list2)
</source>You should have been successful in changing the value of your list.<br><br>
:#Now, try changing the value of your previously-created tuple by issuing:<source lang="python">
t2[1] = 10
</source>Did it work? Once created the tuple values will not be able to change.<br><br>If you would like a tuple with different values than the tuple you currently have, then you must create a new one.<br><br>
:#To create The following creates a new tuple, issue (t3) with a contents from a slice of the t2 tuple. Slicing works the followingsame way for tuples as for lists:<source lang="python">
t3 = t2[2:3]
</source>
for item in t1:
print('item: ' + item)