Skip to content

Commit 83481ca

Browse files
authored
Create les7_tuples.py
Tuples
1 parent 3023c2e commit 83481ca

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

les7_tuples.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#https://newdigitals.org/2024/01/23/basic-python-programming/#tuples
2+
#Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered and unchangeable or immutable.
3+
#It is an ordered collection, so it preserves the order of elements in which they were defined.
4+
#Since tuples are indexed, they can have items with the same value (duplicates).
5+
#Tuple items can be of any data type with strings, integers and Boolean values.
6+
#Tuples are written with round brackets, separated by a comma:
7+
thistuple = ("apple", "banana", "cherry")
8+
print(thistuple)
9+
Output:
10+
('apple', 'banana', 'cherry')
11+
12+
#As with Lists, you can use the len() function
13+
thistuple = ("apple", "banana", "cherry")
14+
print(len(thistuple))
15+
Output:
16+
3
17+
#To create a tuple with only one item, you have to add a comma after the item
18+
thistuple = ("apple",)
19+
print(type(thistuple))
20+
Output:
21+
<class 'tuple'>
22+
#It is also possible to use the tuple() constructor to make a tuple
23+
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
24+
print(thistuple)
25+
Output:
26+
('apple', 'banana', 'cherry')
27+
See below the Python programs to demonstrate the addition of elements in a Tuple:
28+
# Creating an empty Tuple
29+
Tuple1 = ()
30+
print("Initial empty Tuple: ")
31+
print(Tuple1)
32+
33+
# Creating a Tuple
34+
# with the use of string
35+
Tuple1 = ('Geeks', 'For')
36+
print("\nTuple with the use of String: ")
37+
print(Tuple1)
38+
39+
# Creating a Tuple with
40+
# the use of list
41+
list1 = [1, 2, 4, 5, 6]
42+
print("\nTuple using List: ")
43+
print(tuple(list1))
44+
45+
# Creating a Tuple
46+
# with the use of built-in function
47+
Tuple1 = tuple('Geeks')
48+
print("\nTuple with the use of function: ")
49+
print(Tuple1)
50+
51+
Output:
52+
Initial empty Tuple:
53+
()
54+
55+
Tuple with the use of String:
56+
('Geeks', 'For')
57+
58+
Tuple using List:
59+
(1, 2, 4, 5, 6)
60+
61+
Tuple with the use of function:
62+
('G', 'e', 'e', 'k', 's')
63+
64+
#Read more:
65+
66+
#Concatenation of Tuples
67+
#Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing can also be done to lists and arrays.
68+
#The entire tuple gets deleted by the use of del() method.
69+
#Built-In Methods (index, count) & Functions (all, any, len, enumerate, min, max, sum, sorted, tuple)
70+

0 commit comments

Comments
 (0)