9/4/26About 1 minAbout 178 words
Concept: Tuple methods & operators
A tuple can be used with all methods for lists, except for those that modify the contents of a list.
len(): Returns the number of items in the tuple.ftp_socket = ('ftp', '192.168.1.65', '21') print(len(ftp_socket)) # Output: 3join(): Joins the elements of a tuple into a string, using a specified separator.ftp_socket = ('ftp', '192.168.1.65', '21') print(' '.join(ftp_socket)) # Output: ftp 192.168.1.65 21count(): Returns the number of occurrences of a specified item in the tuple.users = ('Alice', 'Bob', 'Eve', 'Alice') print(users.count('Alice')) # Output: 2
All operators that work with lists also work with tuples.
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Concatenation | ('a', 'b') + ('c', 'd') | ('a', 'b', 'c', 'd') |
* | Repetition | ('a', 'b') * 2 | ('a', 'b', 'a', 'b') |
< | Less than | ('a', 'b') < ('c', 'd') | True |
> | Greater than | ('a', 'b') > ('c', 'd') | False |
== | Equal to | ('a', 'b') == ('a', 'b') | True |
!= | Not equal to | ('a', 'b') != ('c', 'd') | True |
in | Membership | 'a' in ('a', 'b') | True |
not in | Not membership | 'c' not in ('a', 'b') | True |