Can tuples be in a list?

In this post we will talk about creating Python Lists of Tuples and how they can be used.

Python Lists

Lists in Python are simply an array. Here is a basic list of my favorite WoW Classes:

awesomeList = ['paladin', 'rogue', 'priest', 'warrior', 'druid']

Lists are created using brackets []

We can add stuff to the end of our list with append[] : 

In [6]: awesomeList.append["warlock"] In [7]: awesomeList Out[7]: ['paladin', 'rogue', 'priest', 'warrior', 'druid', 'warlock']

Items in a list have an index starting at 0 called an offset. So we can reference specific items in our list like this:

In [7]: awesomeList Out[7]: ['paladin', 'rogue', 'priest', 'warrior', 'druid', 'warlock'] In [8]: awesomeList[0] Out[8]: 'paladin' In [9]: awesomeList[3] Out[9]: 'warrior'

Change items by using the offset as well:

In [10]: awesomeList[3] = "monk" In [11]: awesomeList Out[11]: ['paladin', 'rogue', 'priest', 'monk', 'druid', 'warlock']

Lastly, you can delete items from the list by using remove[] : 

In [12]: awesomeList.remove['monk'] In [13]: awesomeList Out[13]: ['paladin', 'rogue', 'priest', 'druid', 'warlock']

There is more to lists but that should be enough for the purposes of this post. You can learn more from the Python reference documentation if you wish. Onward to tuples:

Python Tuples

Tuples are very similar to lists, but tuples are immutable. This means after they are created you can't change them.

Let's create a tuple from the same list of WoW classes above.

In [14]: awesomeTuple = ['paladin', 'rogue', 'priest', 'warrior', 'druid'] In [15]: awesomeTuple Out[15]: ['paladin', 'rogue', 'priest', 'warrior', 'druid']

With tuples we can "unpack" the values like this:

In [16]: belkas, gorkin, landril, maxilum, ferral = awesomeTuple In [17]: belkas Out[17]: 'paladin' In [18]: maxilum Out[18]: 'warrior'

You can also create a tuple from a list.

In [20]: tuple[awesomeList] Out[20]: ['paladin', 'rogue', 'priest', 'druid', 'warlock']

Check out the Python reference documentation for more info on tuples.

Now that we have a good intro to Python Lists and Tuples we can get to the meat of this tutorial.

Python Lists of Tuples

We can create lists of tuples. This is great for working with stuff like log files.

Let's say we parsed in a log file and we have the status code and message from an Apache2 weblog.

We could then represent this data using Python lists of tuples. Here is an overly-simplified example:

In [21]: logs = [ ...: ['HTTP_OK', 'GET /index.html'], ...: ['HTTP_NOT_FOUND', 'GET /index.htmll'] ...: ]

This lets us do some pretty cool operations like count the number of errors.

In [29]: errorCount = 0 ...: for log in logs: ...: status, message = log ...: if status is not 'HTTP_OK': ...: errorCount += 1 ...: In [30]: errorCount Out[30]: 1

Why use tuples over lists? Tuples use less space for one. Using the example above for parsing a log file, if the log file is big then using tuples reduces the amount of memory used.

I hope you have enjoyed this article.

Lists and Tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type including the nothing type defined by the None Keyword.

Lists and Tuples are similar in most context but there are some differences which we are going to find in this article.

Syntax Differences

Syntax of list and tuple is slightly different. Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis [].

Example 1.1: Creating List vs. Creating Tuple

list_num = [1,2,3,4] tup_num = [1,2,3,4] print[list_num] print[tup_num]

Output:

[1,2,3,4] [1,2,3,4]

Above, we defined a variable called list_num which hold a list of numbers from 1 to 4.The list is surrounded by brackets []. Also, we defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis [].

In python we have type[] function which gives the type of object created.

Example 1.2: Find type of data structure using type[] function

type[list_num] type[tup_num]

Output:

list tuple

Mutable List vs Immutable Tuples

List has mutable nature i.e., list can be changed or modified after its creation according to needs whereas tuple has immutable nature i.e., tuple can’t be changed or modified after its creation.

Example 2.1: Modify an item List vs. Tuple

list_num[2] = 5 print[list_num] tup_num[2] = 5

Output:

[1,2,5,4] Traceback [most recent call last]: File "python", line 6, in TypeError: 'tuple' object does not support item assignment

In above code we assigned 5 to list_num at index 2 and we found 5 at index 2 in output. Also, we assigned 5 to tup_num at index 2 and we got type error. We can't modify the tuple due to its immutable nature.

Note: As the tuple is immutable these are fixed in size and list are variable in size.

Available Operations

Lists has more builtin function than that of tuple. We can use dir[[object]] inbuilt function to get all the associated functions for list and tuple.

Example 3.1: List Directory

dir[list_num]

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Example 3.2: Tuple Directory

dir[tup_num]

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

We can clearly see that, there are so many additional functionalities associated with a list over a tuple.We can do insert and pop operation, removing and sorting elements in the list with inbuilt functions which is not available in Tuple.

Size Comparison

Tuples operation has smaller size than that of list, which makes it a bit faster but not that much to mention about until you have a huge number of elements.

Example 5.1: Calculate size of List vs. Tuple

a= [1,2,3,4,5,6,7,8,9,0] b= [1,2,3,4,5,6,7,8,9,0] print['a=',a.__sizeof__[]] print['b=',b.__sizeof__[]]

Output:

a= 104 b= 120

In above code we have tuple a and list b with same items but the size of tuple is less than the list.

Different Use Cases

At first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures

  1. Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed.
     
  2. Tuples are commonly used as the equivalent of a dictionary without keys to store data. For Example, [['Swordfish', 'Dominic Sena', 2001], ['Snowden', ' Oliver Stone', 2016], ['Taxi Driver', 'Martin Scorsese', 1976]] Above example contains tuples inside list which has a list of movies.
     
  3. Reading data is simpler when tuples are stored inside a list. For example, [[2,4], [5,7], [3,8], [5,9]] is easier to read than [[2,4], [5,7], [3,8], [5,9]]

Tuple can also be used as key in dictionary due to their hashable and immutable nature whereas Lists are not used as key in a dictionary because list can’t handle __hash__[] and have mutable nature.

key_val= {['alpha','bravo']:123} #Valid key_val = {['alpha','bravo']:123} #Invalid

Key points to remember:

  1. The literal syntax of tuples is shown by parentheses [] whereas the literal syntax of lists is shown by square brackets [] .
  2. Lists has variable length, tuple has fixed length.
  3. List has mutable nature, tuple has immutable nature.
  4. List has more functionality than the tuple.


A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −

tup1 = ['physics', 'chemistry', 1997, 2000]; tup2 = [1, 2, 3, 4, 5 ]; tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −

tup1 = [];

To write a tuple containing a single value you have to include a comma, even though there is only one value −

tup1 = [50,];

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

Live Demo #!/usr/bin/python tup1 = ['physics', 'chemistry', 1997, 2000]; tup2 = [1, 2, 3, 4, 5, 6, 7 ]; print "tup1[0]: ", tup1[0]; print "tup2[1:5]: ", tup2[1:5];

When the above code is executed, it produces the following result −

tup1[0]: physics tup2[1:5]: [2, 3, 4, 5]

Updating Tuples

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

Live Demo #!/usr/bin/python tup1 = [12, 34.56]; tup2 = ['abc', 'xyz']; # Following action is not valid for tuples # tup1[0] = 100; # So let's create a new tuple as follows tup3 = tup1 + tup2; print tup3;

When the above code is executed, it produces the following result −

[12, 34.56, 'abc', 'xyz']

Delete Tuple Elements

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example −

Live Demo #!/usr/bin/python tup = ['physics', 'chemistry', 1997, 2000]; print tup; del tup; print "After deleting tup : "; print tup;

This produces the following result. Note an exception raised, this is because after del tup tuple does not exist any more −

['physics', 'chemistry', 1997, 2000] After deleting tup : Traceback [most recent call last]: File "test.py", line 9, in print tup; NameError: name 'tup' is not defined

Basic Tuples Operations

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter −

Python Expression Results Description
len[[1, 2, 3]] 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!',] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1, 2, 3]: print x, 1 2 3 Iteration

Indexing, Slicing, and Matrixes

Because tuples are sequences, indexing and slicing work the same way for tuples as they do for strings. Assuming following input −

L = ['spam', 'Spam', 'SPAM!'] Python Expression Results Description
L[2] 'SPAM!' Offsets start at zero
L[-2] 'Spam' Negative: count from the right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections

No Enclosing Delimiters

Any set of multiple objects, comma-separated, written without identifying symbols, i.e., brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short examples −

Live Demo #!/usr/bin/python print 'abc', -4.24e93, 18+6.6j, 'xyz'; x, y = 1, 2; print "Value of x , y : ", x,y;

When the above code is executed, it produces the following result −

abc -4.24e+93 [18+6.6j] xyz Value of x , y : 1 2

Built-in Tuple Functions

Python includes the following tuple functions −

Video liên quan

Chủ Đề