|
| 1 | +# Tuple is similar to List, but the difference is that Tuples are immutable (cannot be changed) |
| 2 | +my_tuple = ('Ali', 21, True) # simple tuple |
| 3 | +print(my_tuple) |
| 4 | + |
| 5 | +print(my_tuple[1]) # it will give the value at index 1 |
| 6 | +print(my_tuple[0]) # it will give the value at index 0 |
| 7 | + |
| 8 | +# Looping over a tuple |
| 9 | +for item in my_tuple: |
| 10 | + print(item) |
| 11 | + |
| 12 | +# Convert tuple to list |
| 13 | +new_list = list(my_tuple) |
| 14 | +print(new_list) |
| 15 | + |
| 16 | +# Convert list back to tuple |
| 17 | +new_tuple = tuple(new_list) |
| 18 | +print(new_tuple) |
| 19 | + |
| 20 | +# Tuple slicing |
| 21 | +print(new_tuple[0:1]) |
| 22 | +print(new_tuple[1:]) |
| 23 | + |
| 24 | +# Tuple concatenation |
| 25 | +car_tuple = ('Honda', 'Kia', 'BMW', 'BMW', 'GMC') |
| 26 | +all_tuple = car_tuple + new_tuple |
| 27 | +print(all_tuple) |
| 28 | + |
| 29 | +# Conditional check in tuple |
| 30 | +if 'Honda' in all_tuple: |
| 31 | + print('Yes, Honda is present') |
| 32 | + |
| 33 | +# Count method in tuple |
| 34 | +print(all_tuple.count('BMW')) # how many times 'BMW' appears |
| 35 | + |
| 36 | +# Tuple unpacking |
| 37 | +color = ('red', 'green', 'black') |
| 38 | +(red, green, black) = color |
| 39 | +print(red) |
| 40 | + |
| 41 | +# Nested tuple access |
| 42 | +nested_tuple = ( |
| 43 | + 'red', |
| 44 | + 'green', |
| 45 | + ('red', ('red', 'green', 'black'), 'green', 'black'), |
| 46 | + 'black' |
| 47 | +) |
| 48 | +print(nested_tuple[2][1][0]) # Accessing nested tuple value |
0 commit comments