Is list and tuple same in Python?

This is an example of Python lists:

my_list = [0,1,2,3,4] top_rock_list = ["Bohemian Rhapsody","Kashmir","Sweet Emotion", "Fortunate Son"]

This is an example of Python tuple:

my_tuple = [a,b,c,d,e] celebrity_tuple = ["John", "Wayne", 90210, "Actor", "Male", "Dead"]

Python lists and tuples are similar in that they both are ordered collections of values. Besides the shallow difference that lists are created using brackets "[ ... , ... ]" and tuples using parentheses "[ ... , ... ]", the core technical "hard coded in Python syntax" difference between them is that the elements of a particular tuple are immutable whereas lists are mutable [...so only tuples are hashable and can be used as dictionary/hash keys!]. This gives rise to differences in how they can or can't be used [enforced a priori by syntax] and differences in how people choose to use them [encouraged as 'best practices,' a posteriori, this is what smart programers do]. The main difference a posteriori in differentiating when tuples are used versus when lists are used lies in what meaning people give to the order of elements.

For tuples, 'order' signifies nothing more than just a specific 'structure' for holding information. What values are found in the first field can easily be switched into the second field as each provides values across two different dimensions or scales. They provide answers to different types of questions and are typically of the form: for a given object/subject, what are its attributes? The object/subject stays constant, the attributes differ.

For lists, 'order' signifies a sequence or a directionality. The second element MUST come after the first element because it's positioned in the 2nd place based on a particular and common scale or dimension. The elements are taken as a whole and mostly provide answers to a single question typically of the form, for a given attribute, how do these objects/subjects compare? The attribute stays constant, the object/subject differs.

There are countless examples of people in popular culture and programmers who don't conform to these differences and there are countless people who might use a salad fork for their main course. At the end of the day, it's fine and both can usually get the job done.

To summarize some of the finer details

Similarities:

  1. Duplicates - Both tuples and lists allow for duplicates
  2. Indexing, Selecting, & Slicing - Both tuples and lists index using integer values found within brackets. So, if you want the first 3 values of a given list or tuple, the syntax would be the same:

    >>> my_list[0:3] [0,1,2] >>> my_tuple[0:3] [a,b,c]
  3. Comparing & Sorting - Two tuples or two lists are both compared by their first element, and if there is a tie, then by the second element, and so on. No further attention is paid to subsequent elements after earlier elements show a difference.

    >>> [0,2,0,0,0,0]>[0,0,0,0,0,500] True >>> [0,2,0,0,0,0]>[0,0,0,0,0,500] True

Differences: - A priori, by definition

  1. Syntax - Lists use [], tuples use []

  2. Mutability - Elements in a given list are mutable, elements in a given tuple are NOT mutable.

    # Lists are mutable: >>> top_rock_list ['Bohemian Rhapsody', 'Kashmir', 'Sweet Emotion', 'Fortunate Son'] >>> top_rock_list[1] 'Kashmir' >>> top_rock_list[1] = "Stairway to Heaven" >>> top_rock_list ['Bohemian Rhapsody', 'Stairway to Heaven', 'Sweet Emotion', 'Fortunate Son'] # Tuples are NOT mutable: >>> celebrity_tuple ['John', 'Wayne', 90210, 'Actor', 'Male', 'Dead'] >>> celebrity_tuple[5] 'Dead' >>> celebrity_tuple[5]="Alive" Traceback [most recent call last]: File "", line 1, in TypeError: 'tuple' object does not support item assignment
  3. Hashtables [Dictionaries] - As hashtables [dictionaries] require that its keys are hashable and therefore immutable, only tuples can act as dictionary keys, not lists.

    #Lists CAN'T act as keys for hashtables[dictionaries] >>> my_dict = {[a,b,c]:"some value"} Traceback [most recent call last]: File "", line 1, in TypeError: unhashable type: 'list' #Tuples CAN act as keys for hashtables[dictionaries] >>> my_dict = {["John","Wayne"]: 90210} >>> my_dict {['John', 'Wayne']: 90210}

Differences - A posteriori, in usage

  1. Homo vs. Heterogeneity of Elements - Generally list objects are homogenous and tuple objects are heterogeneous. That is, lists are used for objects/subjects of the same type [like all presidential candidates, or all songs, or all runners] whereas although it's not forced by], whereas tuples are more for heterogenous objects.

  2. Looping vs. Structures - Although both allow for looping [for x in my_list...], it only really makes sense to do it for a list. Tuples are more appropriate for structuring and presenting information [%s %s residing in %s is an %s and presently %s % ["John","Wayne",90210, "Actor","Dead"]]

List and Tuple are built-in container types defined in Python. Objects of both these types can store different other objects that are accessible by index. List as well as tuple is a sequence data type, just as string. List as well as tuple can store objects which need not be of same type.

List : A List is an ordered collection of items [which may be of same or different types] separated by comma and enclosed in square brackets.

In [1]: L1=[10,25.5,3+2j,"Hello"] L1 Out[1]: [10, 25.5, [3+2j], 'Hello']

In above list, each item is of different type. Further, each item is accessible by positional index starting from 0. Hence L1[2] will return 25.5

In [2]: L1[1] Out[2]: 25.5

Tuple: Tuple looks similar to list. The only difference is that comma separated items of same or different type are enclosed in parentheses. Individual items follow zero based index, as in list or string.

In [3]: T1=[10,25.5,3+2j,"Hello"] T1 Out[3]: [10, 25.5, [3+2j], 'Hello'] In [4]: T1[1] Out[4]: 25.5

Difference between List and Tuple:

The obvious difference is the use of square brackets [] in List and parentheses [] in tuple as enclosures. However, the important difference is that List as a mutable object and Tuple is an immutable object.

If contents of an object can be modified in place, after it has been instantiated, is a mutable object. On the other hand, any operation on immutable object that tries to modify its contents is prohibited.

In above example, any item in the list L1 can be assigned with different value. Let us change value of item at index=2 from 3+2j to 1.22E-5

In [5]: L1[2]=1.22E-5 L1 Out[5]: [10, 25.5, 1.22e-05, 'Hello']

The built-in List class has different methods that allow various operations on List object [such as insertion, deletion, sorting etc]

However, any such operation is not possible with Tuple object. If we try to modify T1 by changing value of item at index=2 to 1.22E-5, TypeError exception is raised.

In [6]: T1[2]=1.22E-5 T1 --------------------------------------------------------------------------- TypeError                                Traceback [most recent call last] in [] ----> 1 T1[2]=1.22E-5       2 T1 TypeError: 'tuple' object does not support item assignment

Following built-in functions can be used along with List as well as Tuple.

len[]Returns number of elements in list/tuple
max[]If list/tuple contains numbers, largest number will be returned. If list/tuple contains strings, one that comes last in alphabetical order will be returned.
min[]If list/tuple contains numbers, smallest number will be returned. If list/tuple contains strings, one that comes first in alphabetical order will be returned.
sum[]Returns addition of all elements in list/tuple
sorted[]sorts the elements in list/tuple
In [7]: L1=[10,30,50,20,40] T1=[10,50,30,40,20] print [len[L1]] print [len[T1]] print ['max of L1', max[L1]] print ['max of T1', max[T1]] print ['min of L1', min[L1]] print ['min of T1', min[T1]] print ['sum of L1', sum[L1]] print ['sum of T1', sum[T1]] print ['L1 in sorted order', sorted[L1]] print ['T1 in sorted order', sorted[T1]] Out[7]: 5 5 max of L1 50 max of T1 50 min of L1 10 min of T1 10 sum of L1 150 sum of T1 150 L1 in sorted order [10, 20, 30, 40, 50] T1 in sorted order [10, 20, 30, 40, 50]

If items in list/tuple are strings, min[] and max[] functions returns string that comes first/last in alphabetical order. If list/tuple is made up of numeric and nonnumeric values, TypeError exception is raised as comparison of dissimilar objects is not possible.

In [8]: L2=['pen', 'book','computer', 'table', 'file'] T2=['pen', 'book','computer', 'table', 'file'] print ['max of L2', max[L2]] print ['max of T2', max[T2]] print ['min of L2', min[L2]] print ['min of T2', min[T2]] max of L2 table max of T2 table min of L2 book min of T2 book Out [9]: L3=[100, "hundred", 0.001] print ['max of L3', max[L3]] --------------------------------------------------------------------------- TypeError                                Traceback [most recent call last] in []     1 L3=[100, "hundred", 0.001] ----> 2 print ['max of L3', max[L3]] TypeError: '>' not supported between instances of 'str' and 'int'

The built-in list class has following methods to perform various operations on list object. Following methods allow new items to be added to list.

append[]appends an object to end  of list
copy[]makes a shallow copy of list  
count[]return number of occurrences of value in list
extend[]extends the list by appending elements from another list/tuple  
insert[]inserts object in the list before given index  
In [10]: L1=[10,30,50,20,40] L1.append[100] #appends new item print ["after append",L1] L1.insert[2,30] #inserts new value at index print ['after insert',L1] c=L1.count[30] print ['count of 30',c] L1.extend[[11,22,33]] print ['after extend', L1]         Out [10]: after append [10, 30, 50, 20, 40, 100] after insert [10, 30, 30, 50, 20, 40, 100] count of 30 2 after extend [10, 30, 30, 50, 20, 40, 100, 11, 22, 33]

Following methods are used to remove items from given list.

pop[]removes and returns item at given index .  Raises IndexError if list is empty or index is out of range.
remove[]removes first occurrence of value in the list. Raises ValueError if the value is not present.
clear[]remove all items from the list
In [11]: p=L1.pop[] print ['item popped:', p] print ['list after popping', L1] L1.remove[100] print ['after removing value :',L1] L1.clear[] print ['all cleared:', L1]        Out [11]: item popped: 33 list after popping [10, 30, 30, 50, 20, 40, 100, 11, 22] after removing value : [10, 30, 30, 50, 20, 40, 11, 22] all cleared: []

Following methods rearrange sequence of items in the list

reverse[]reverses the list in place
sort[]sorts the list in place
In [12]: L1=[10, 30, 30, 50, 20, 40, 11, 22] print ['original list :', L1] L1.reverse[] print ['after reversing:',L1] L1.sort[] print ["sorted list: ", L1] Out [12]: original list : [10, 30, 30, 50, 20, 40, 11, 22] after reversing: [22, 11, 40, 20, 50, 30, 30, 10] sorted list:  [10, 11, 20, 22, 30, 30, 40, 50]

If you recall, tuple is an immutable object. Hence the tuple class doesn’t have similar methods perform insertion, deletion or rearrangement of items.

Conversion functions

All sequence type objects [string, list and tuple] are inter-convertible. Python’s built-in functions for this purpose are explained below:

list[]converts a tuple or string to list
tuple[]converts list or string to tuple
str[]returns string representation of list or tuple object
In [13]: L1=[10, 30, 30, 50, 20, 40, 11, 22] T1=tuple[L1] print [T1] [10, 30, 30, 50, 20, 40, 11, 22] In [14]: T1=[10,50,30,40,20] L1=list[T1] print [L1] [10, 50, 30, 40, 20] In [15]: s1="Hello" L2=list[s1] print ['string to list:', L2] T2=tuple[s1] print ['string to tuple', T2] string to list: ['H', 'e', 'l', 'l', 'o'] string to tuple ['H', 'e', 'l', 'l', 'o'] In [16]: s1=str[L1] s2=str[T1] print ['list to string',s1] print ['tuple to string',s2] list to string [10, 50, 30, 40, 20] tuple to string [10, 50, 30, 40, 20]

When a list or tuple is converted to string by str[] function, the string representation is not exactly similar to word, but list or tuple surrounded by single quote marks. To form a continuous sequence of characters in the list, use join[] method of string object.

In [17]: L2=['H', 'e', 'l', 'l', 'o'] s1=str[L2] s1 Out[17]: "['H', 'e', 'l', 'l', 'o']" In [18]: s2="".join[L2] print ['string from list items:', s2] string from list items: Hello

In this chapter, we discussed the list and tuple objects, their functions and methods. In next chapter we shall learn about dictionary data type.

Video liên quan

Chủ Đề