ما هي الـ Tuples في بايثون؟ دليل شامل للمبتدئين

اليوم سنتعرف على بنية بيانات مهمة جداً تسمى Tuple (تُنطق "تيوبل" أو "تابل"). إذا كنت تتذكر درس الـ Lists، فستجد أن الـ Tuples تشبهها كثيراً ولكن مع فرق رئيسي واحد مهم جداً!

ما هو الـ Tuple؟

الـ Tuple هو نوع من الـ Containers في بايثون يستخدم لتخزين Set من العناصر مرتبة حسب ترتيب محدد. تخيله كصندوق صغير يمكنك وضع عدة أشياء بداخله، ولكن بمجرد إغلاقه لا يمكنك تغيير محتوياته!

الـ Properties الرئيسية للـ Tuple:

  • مرتب (Ordered): العناصر تحتفظ بترتيب إضافتها
  • يسمح بالتكرار (Allows duplicates): يمكن أن يحتوي على عناصر مكررة
  • غير قابل للتغيير (Immutable): لا يمكن تعديله بعد الإنشاء

كيفية إنشاء Tuple

لإنشاء tuple، نضع العناصر بين قوسين عاديين () ويفصل بينها بفواصل:

# Create an empty tuple
empty_tuple = ()
print(empty_tuple)  # ()

# Create a tuple containing numbers
numbers = (1, 2, 3, 4, 5)
print(numbers)  # (1, 2, 3, 4, 5)

# Create a tuple containing strings
fruits = ("apple", "banana", "orange")
print(fruits)  # ('apple', 'banana', 'orange')

# Create a mixed tuple
mixed = (1, "text", 3.14, True)
print(mixed)  # (1, 'text', 3.14, True)

ملاحظة مهمة: إذا كنت تريد إنشاء tuple يحتوي على عنصر واحد فقط، يجب إضافة فاصلة بعد العنصر:

# This will be just a number and not a tuple
not_tuple = (5)
print(type(not_tuple))  # <class 'int'>

# This is a correct tuple with one element
correct_tuple = (5,)
print(type(correct_tuple))  # <class 'tuple'>

الوصول إلى عناصر الـ Tuple

يمكنك الوصول إلى عناصر الـ Tuple باستخدام الفهرس (Index) تماماً مثل الـ Lists:

# Create tuple
colors = ("red", "green", "blue", "yellow")

# Access the first element (index 0)
print(colors[0])  # red

# Access the third element (index 2)
print(colors[2])  # blue

# Access the last element
print(colors[-1])  # yellow

# slicing to extract part of the tuple
print(colors[1:3])  # ('green', 'blue')

ما الفرق بين Tuple و List؟

هذا سؤال مهم جداً! إليك الفروق الرئيسية:

الميزة Tuple List
القابلية للتغيير غير قابل للتغيير (Immutable) قابل للتغيير (Mutable)
الأقواس المستخدمة () []
الأداء أسرع في التكرار أبطأ قليلاً
الاستخدام للبيانات الثابتة للبيانات المتغيرة
# Example showing the difference
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)

# I can modify the list
my_list[0] = 10 # works
print(my_list)  # [10, 2, 3]

# I cannot modify the tuple
# my_tuple[0] = 10 # Error! does not work

العمليات الأساسية على الـ Tuples

1. التكرار (Looping)

days = ("Saturday", "Sunday", "Monday")

# Iteration using for loop
for day in days:
    print(day)

2. التحقق من وجود عنصر

fruits = ("apple", "banana", "orange")

# Check if the element exists
print("apple" in fruits)  # True
print("strawberry" in fruits)  # False

3. دمج الـ Tuples

tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")

# Merge the tuples
combined = tuple1 + tuple2
print(combined)  # (1, 2, 3, 'a', 'b', 'c')

4. تكرير الـ Tuple

numbers = (1, 2)
repeated = numbers * 3
print(repeated)  # (1, 2, 1, 2, 1, 2)

الطول والعد

# Get number of elements
students = ("Ahmed", "Fatima", "Mohamed", "Zainab")
print(len(students))  # 4

# Count occurrences of a specific element
numbers = (1, 2, 3, 2, 1, 2)
print(numbers.count(2))  # 3 (Number 2 repeats 3 times)

# Get position of an element
print(numbers.index(3))  # 2 (Number 3 is at index 2)

متى نستخدم الـ Tuples؟

  1. للبيانات الثابتة التي لا تتغير (مثل أيام الأسبوع، أشهر السنة)
  2. كلمات المرور أو البيانات الحساسة التي لا نريد تعديلها
  3. كإرجاع للدوال عندما نريد إرجاع أكثر من قيمة
  4. كأساس للـ Dictionaries (سنتعلمها لاحقاً)
# Example: Returning multiple values from a function
def get_student_info():
    name = "Ahmed"
    age = 20
    grade = "A"
    return name, age, grade  # This will return as a tuple

student_info = get_student_info()
print(student_info)  # ('Ahmed', 20, 'A')

نصائح عملية

  1. استخدم الـ Tuples عندما تعلم أن البيانات لن تتغير
  2. الـ Tuples أكثر أماناً من الـ Lists للبيانات الثابتة
  3. يمكنك تحويل الـ List إلى Tuple والعكس
  4. الـ Tuples أسرع في المعالجة من الـ Lists
# Convert between list and tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)  # Convert list to tuple
new_list = list(my_tuple)  # Convert tuple to list