Tuples in Python
June 21, 2017
Categorised in: Python
- Tuples are very much like lists but the difference is that tuples cannot be changed.
- Tuples are denoted by: () whereas lists are denoted by: []
- To access element in tuple we make use of square brackets. E.g. tup[0]
- Tuples have similar functions as list as they are:
- cmp(tup1, tup2)
- len(tup)
- max(tup)
- min(tup)
- tuple(sequence)
- Let’s see tuples in action:
>>> tup = ()
>>> tup = ("xyz", "xyz")
>>> tup
('xyz', 'xyz')
>>> tup = (
... ("one", "one"),
... ("two", "two"),
... )
>>> tup
(('one', 'one'), ('two', 'two'))
>>> tup[0]
('one', 'one')
>>> tup[0][0]
'one'
>>> tup += ("three", 4)
>>> tup
(('one', 'one'), ('two', 'two'), 'three', 4)
>>> tup += (("three", 4),)
>>> tup
(('one', 'one'), ('two', 'two'), 'three', 4, ('three', 4))
>>> # this is like a list within a list
...
>>> some_list = []
>>> abc = ["one", "one"]
>>> some_list.append(abc)
>>> some_list
[['one', 'one']]
>>> # So tuples are used in a way like dictionary are but based on positions
...
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.