-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython_tuples.py
More file actions
46 lines (31 loc) · 1.27 KB
/
python_tuples.py
File metadata and controls
46 lines (31 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Hello World program in Python
print("Example of Python Tuples\n")
# Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
# You can access tuple items by referring to the index number:
# Return the item in position 1:
print(thistuple[1])
# You can loop through the tuple items by using a for loop.
# Iterate through the items and print the values:
for x in thistuple:
print(x)
# To determine if a specified item is present in a tuple use the in keyword:
# Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
# To determine how many items a list have, use the len() method:
# Print the number of items in the tuple:
print(len(thistuple))
# Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
# Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
# You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
# The del keyword can delete the tuple completely:
del thistuple
print(thistuple) # this will raise an error because the tuple no longer exists