Python tuple array list

Python Tutorials: Difference between List & Array & Tuple & Set & Dict

Mutable means that you can manipulate the list by adding to it, removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. The objects may be any object type in python, from other lists to functions to custom objects. Square brackets enclose the list values .

Mutable means that you can manipulate an array by adding or removing elements, updating already existing elements, etc. Sequence means that the elements are ordered, and indexed to start at index 0. However, unlike lists, arrays can only contains items of the same data type such as Ints, Floats, or Characters.

Immutable

Immutable means that once a tuple is created, you cannot manipulate its contents, for example removing, updating or adding elements. Similar to lists above, the elements are in an ordered and indexed Sequence and can contain any python Objects. However, the tuple is created using parentheses, which are just normal brackets().

odered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

Читайте также:  Найти все делители натурального числа python

If you add new items to a list, the new items will be placed at the end of the list.

Unordered

Unordered means that they cannot be indexed. Key-value pairs means each element has a key which stores the value, and you can access an element’s value by its key.

Lists

A list is of an ordered collection data type that is mutable which means it can be easily modified and we can change its data values and a list can be indexed, sliced, and changed and each element can be accessed using its index value in the list. The following are the main characteristics of a List:

  • The list is an ordered collection of data types.
  • The list is mutable.
  • List are dynamic and can contain objects of different data types.
  • List elements can be accessed by index number.
# Python program to demonstrate List list = ["mango", "strawberry", "orange", "apple", "banana"] print(list) # we can specify the range of the # index by specifying where to start # and where to end print(list[2:4]) # we can also change the item in the # list by using its index number list[1] = "grapes" print(list[1]) 

array

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The following are the main characteristics of an Array:

  • An array is an ordered collection of the similar data types.
  • An array is mutable.
  • An array can be accessed by using its index number.
# Python program to demonstrate # Creation of Array # importing "array" for array creations import array as arr # creating an array with integer type a = arr.array('i', [1, 2, 3]) # printing original array print ("The new created array is : ", end =" ") for i in range (0, 3): print (a[i], end =" ") print() # creating an array with float type b = arr.array('d', [2.5, 3.2, 3.3]) # printing original array print ("The new created array is : ", end =" ") for i in range (0, 3): print (b[i], end =" ") 

tuple

A tuple is an ordered and an immutable data type which means we cannot change its values and tuples are written in round brackets. We can access tuple by referring to the index number inside the square brackets. The following are the main characteristics of a Tuple:

  • Tuples are immutable and can store any type of data type.
  • it is defined using ().
  • it cannot be changed or replaced as it is an immutable data type.
tuple = ("orange","apple","banana") print(tuple) # we can access the items in # the tuple by its index number print(tuple[2]) #we can specify the range of the # index by specifying where to start # and where to end print(tuple[0:2]) 

Sets

We cannot talk about python data structures without mentioning Sets, which we will not get into much details in this article.

Sets are unordered collections of unique objects enclosed by curly braces<> — not to be confused with dictionaries which are also enclosed with curly braces.

Unordered means the elements are not ordered therefore cannot be indexed. Unique means that a set cannot store duplicate values and are therefore very handy for removing duplicates from lists. You can store any python objects in a set. A set is created using Set=. You can convert a list into a set using Set(list).

Sets have their own unique operations for merging two sets. These are union() function or | operator, intersection() function or & operator, and the difference() function or — operator.

Syntax Differences

list_num = [1,2,3,4] tup_num = (1,2,3,4) print(list_num) print(tup_num) type(list_num) type(tup_num)

List of functions of “list”

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.

list_num = [1,2,3,4] c=dir(list_num) print(c) 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']

List of functions of “tuple”

tup_num = (1,2,3,4) d=dir(tup_num) print(d) 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']

List of functions of “array”

arrays = "123456" a=dir(arrays) print(a) ['__add__' '__class__' '__contains__' '__delattr__' '__dir__' '__doc__' '__eq__' '__format__' '__ge__' '__getattribute__' '__getitem__' '__getnewargs__' '__gt__' '__hash__' '__init__' '__init_subclass__' '__iter__' '__le__' '__len__' '__lt__' '__mod__' '__mul__' '__ne__' '__new__' '__reduce__' '__reduce_ex__' '__repr__' '__rmod__' '__rmul__' '__setattr__' '__sizeof__' '__str__' '__subclasshook__' 'capitalize' 'casefold' 'center' 'count' 'encode' 'endswith' 'expandtabs' 'find' 'format' 'format_map' 'index' 'isalnum' 'isalpha' 'isascii' 'isdecimal' 'isdigit' 'isidentifier' 'islower' 'isnumeric' 'isprintable' 'isspace' 'istitle' 'isupper' 'join' 'ljust' 'lower' 'lstrip' 'maketrans' 'partition' 'removeprefix' 'removesuffix' 'replace' 'rfind' 'rindex' 'rjust' 'rpartition' 'rsplit' 'rstrip' 'split' 'splitlines' 'startswith' 'strip' 'swapcase' 'title' 'translate' 'upper' 'zfill']

List of functions of “set”

['__and__' '__class__' '__class_getitem__' '__contains__' '__delattr__' '__dir__' '__doc__' '__eq__' '__format__' '__ge__' '__getattribute__' '__gt__' '__hash__' '__iand__' '__init__' '__init_subclass__' '__ior__' '__isub__' '__iter__' '__ixor__' '__le__' '__len__' '__lt__' '__ne__' '__new__' '__or__' '__rand__' '__reduce__' '__reduce_ex__' '__repr__' '__ror__' '__rsub__' '__rxor__' '__setattr__' '__sizeof__' '__str__' '__sub__' '__subclasshook__' '__xor__' 'add' 'clear' 'copy' 'difference' 'difference_update' 'discard' 'intersection' 'intersection_update' 'isdisjoint' 'issubset' 'issuperset' 'pop' 'remove' 'symmetric_difference' 'symmetric_difference_update' 'union' 'update']

List of functions of “dictionaries”

['__class__' '__class_getitem__' '__contains__' '__delattr__' '__delitem__' '__dir__' '__doc__' '__eq__' '__format__' '__ge__' '__getattribute__' '__getitem__' '__gt__' '__hash__' '__init__' '__init_subclass__' '__ior__' '__iter__' '__le__' '__len__' '__lt__' '__ne__' '__new__' '__or__' '__reduce__' '__reduce_ex__' '__repr__' '__reversed__' '__ror__' '__setattr__' '__setitem__' '__sizeof__' '__str__' '__subclasshook__' 'clear' 'copy' 'fromkeys' 'get' 'items' 'keys' 'pop' 'popitem' 'setdefault' 'update' 'values']

Источник

Python List vs Array vs Tuple – Understanding the Differences

In any programming language, the data structures available play an extremely important role. They decide how your data will be stored in the memory and how you can retrieve the data when required. Therefore, the entire process of memory management and processing speed of data are dependent on them. When it comes to python or any modern programming language for that matter, the three data structures stand out and widely used in small to commercial projects. They are array, list, and tuple. They may look similar to many programmers but they were created so that they can be used when they are advantageous in different scenarios. Therefore, one has to understand the differences and correct usage for efficient memory management and data processing.

Differences Between Python List, Array, and Tuple –

Array – We should always start with an array as it appeared in the programming languages earlier than the rest two. Therefore, you would expect its operation to the simple and primitive. An array is a contiguous memory allocation for data storage. The static array always has a predefined size and it is efficient for iterative works as the elements are stored side by side in the dedicated memory locations. It is not that effective when it comes to inserting a new element in between the already present elements.

Similarly, it causes inefficient memory management when you delete an element in between the elements present. Therefore, a static array is suitable only when you need to keep a series of elements side by side and you have to do iterative works through loops. In such a scenario, the memory management and data processing will be faster. If you are already running out of memory space, it can give you errors and you can lose certain elements due to out of range scenario.

To avoid the drawbacks of static arrays to a certain extent, the dynamic array was introduced and the data structures like vectors, array list and likewise fall under the dynamic array. These dynamic arrays can be resized and they can be placed in a scattered manner in the memory space as per availability.

List – The concept of the dynamic array led to list or linked list as some like to call it. As a matter of act, after the introduction of the linked list, the dynamic array data structures started to become less popular. Unlike an array, a linked list is not continuous memory allocation. It has scatted memory allocation technique. Each node of a list consists of two parts. The first part contains the data while the second part is a pointer that had the memory reference of the next node wherever it is placed in the memory. This makes the memory management efficient in all scenarios and you can add or delete nodes in a list effortlessly with extremely high processing speed. Unlike an array, a list can have heterogeneous data.

A modified version of a list is called double linked list where each node has three parts – the data, the reference of the previous node and the reference of the next node. This makes it easy to access any data with a higher speed and perform different iteration swiftly.

Tuple – Tuple is often compared with List as it looks very much like a list. A tuple is actually an object that can contain heterogeneous data. Out of all data structures, a tuple is considered to be the fastest and they consume the least amount of memory. While array and list are mutable which means you can change their data value and modify their structures, a tuple is immutable. Like a static array, a tuple is fixed in size and that is why tuples are replacing array completely as they are more efficient in all parameters. The syntaxes of each one of these data structures are different. If you have a dataset which will be assigned only once and its value should not change again, you need a tuple.

Conclusion –

The concept of array is becoming obsolete as it is a bad memory management option and there are various shortcomings in its operation that makes it have limited usage. If you really need to use a static array in your program, you should use tuple as it is better at memory management than an array and does the same job as a static array. The only thing it does not do is that it does not let you change it. This property makes your data safe.

But if changing the values and inserting new data in between already available data is required, then the linked list is the ideal choice as it manages memory and data perfectly and the execution time in big projects will come down significantly. You can perform different types of operations on a list as per your requirements.

Источник

Оцените статью