A Tuple is a collection of Python objects
• A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable. • A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The parentheses are optional Example: empty_tuple = () print (empty_tuple)
• tup = ('python', 'geeks') • print(tup) • • tuple 1 = (0, 1, 2, 3) tuple 2 = ('python', 'geek') # Concatenating above two print(tuple 1 + tuple 2) • Output: • (0, 1, 2, 3, 'python', 'geek')
• count() method searches the given element in a tuple and returns how many times the element has occurred in it. • The syntax of count() method is: • tuple. count(element)
• • • • # vowels tuple vowels = ('a', 'e', 'i', 'o', 'e', 'i', 'u') # count element 'i' count = vowels. count('i') # print count print('The count of i is: ', count) # count element 'p' count = vowels. count('p') # print count print('The count of p is: ', count)
• • #code to test that tuples are immutable tuple 1 = (0, 1, 2, 3) tuple 1[0] = 4 print(tuple 1) • # code to test slicing • • tuple 1 = (0 , 1, 2, 3) print(tuple 1[1: ]) print(tuple 1[: : -1]) print(tuple 1[2: 4])
Tuple Methods Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found
- Slides: 6