Python Tuples
Tuple
tuple مجموعه ای مرتب و غیرقابل تغیر است که در پایتون داخل () نوشته می شود.
مثال:
:Create a Tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Access tuples Item
با استفاده از اندیس ها میتوانیم به عناصر یک تاپل دسترسی پیدا کنیم.
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
هنگامی که یک tuple ایحاد می شود ما نمی توانیم مقادیر آن را تغیر دهیم بنابراین tuple ها غیر قابل تغیر هستند.
مثال:
:You cannot change values in a tuple
thistuple = ("apple", "banana", "cherry")
thistuple[1] = "blackcurrant"
# The values will remain the same:
print(thistuple)
loop Trough a Tuple
شما می توانید با استفاده از حلقه for روی آیتم های tuple پیمایش کنید.
مثال:
:Iterate through the items and print the values
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
در مورد for loops در بخش Python For Loops بیشتر یاد خواهیم گرفت.
check If Item Exists
برای تعیین وجود یک آیتم مشخص در یک تاپل از کلمه کلیدی in استفاده می کنیم.
مثال:
:Check if “apple” is present in the tuple
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Tuple Length
برای مشخص کردن تعداد آیتم های یک Tuple از تابع ( )len استفاده می کنیم.
مثال:
:Print the number of items in the tuple
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Add Items
زمانی که یک Tuple ایجاد می شود شما نمی توانید آیتمی به آن اضافه کنید, Tuple ها غیر قابل تغیر هستند.
⊗مثال:
:You cannot add items to a tuple
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Remove Item
هشدار: شما نمی توانید آیتم ها را از Tuple حذف کنید.
Tuple ها غیر قابل تغیر هستند بنابراین شما نمی توانید آیتمی از آن حذف کنید, اما می توان کل Tuple را به صورت کامل حذف کرد.
مثال:
:The del keyword can delete the tuple completely
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
The Tuple( ) Constructor
همجنین این امکان وجود دارد تا از تابع ()tuple سازنده استفاده کنیم تا یک tuple جدید بسازیم.
مثال:
:Using the tuple() method to make a tuple
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Tuple Methods
پایتون دارای دو متد از پیش ساخته شده است که می توانیم برای tuple از آن استفاده کنیم.