python list append

By | March 4, 2019

Python List-: Python has a powerful built in list types. Lists  are like array. A list in Python is much the same thing as an array in Java or C or any other language. It is  an ordered collection of objects. we create a list by enclosing a comma-separated list of elements in square brackets as like

# This assigns a five-element list to x
x = [1, 2, 3,4,5]

Arrays in Python-: A typed array module available in Python provides arrays based on C data types. Information on its use can be found in the Python Library Reference. we look into it only if we really need the performance improvement. If a situation calls for numerical computations, we should consider using.

Unlike lists in other languages Python lists can contain different types of elements such a list element can be any Python object. Here is a list that contains a variety of elements.

# First element is a number, second is a string, third is another list.
x = [2, "two", [1, 2, 3,4]]

Probably the most basic built-in list function is the len function, which returns the number of elements in a list.

>> x = [2, "two", [1, 2, 3]]
>>> len(x)
3

In the len function doesn’t count the items in the inner nested list.

List Indices-: Understanding how list indices work will make Python much more useful to us.

Elements can be extracted from a Python list by using a notation like C’s array indexing. Like C and many other languages Python starts counting from 0,asking for element 0 returns the first element of the list, asking for element 1 returns the second element, and so forth. As like

>>> x = ["first", "second", "third", "fourth"]
>>> x[0]
'first'
>>> x[2]
'third'

But Python indexing is more flexible than C indexing. If indices are negative numbers then  they indicate positions counting from the end of the list with -1 being the last position in the list –2 being the second-to-last position and so forth. Continuing with the same list x as like

>>> a = x[-1]
>>> a
'fourth'
>>> x[-2]
'third'

 

Modifying List-:  We can use list index notation to modify a list as well as to extract an element from it. Put the index on the left side of the assignment operator

>>> x = [1, 2, 3, 4]
>>> x[1] = "two"
>>> x
[1, 'two', 3, 4]

Slice notation can be used here too. Saying something like list a [index1:index2] = list b causes all elements of list a between index1 and index2 to be replaced by the elements in list b. list b can have more or fewer elements than are removed from list a, in which case the length of list a is altered. we can use slice assignment to do several things as like here

>>> x = [1, 2, 3, 4]
>>> x[len(x):] = [5, 6, 7]               1
>>> x
[1, 2, 3, 4, 5, 6, 7]
>>> x[:0] = [-1, 0]                      2
>>> x
[-1, 0, 1, 2, 3, 4, 5, 6, 7]
>>> x[1:-1] = []                         3
>>> x
[-1, 7]
  • 1 Appends list to end of list
  • 2 Appends list to front of list
  • 3 Removes elements from list

Appending a single element to a list is such a common operation that there are a special append method for it.

>>> x = [1, 2, 3]
>>> x.append("four")
>>> x
[1, 2, 3, 'four']

One problem can occur if we try to append one list to another. The list gets appended as a single element of the main list.

>>> x = [1, 2, 3, 4]
>>> y = [5, 6, 7]
>>> x.append(y)
>>> x
[1, 2, 3, 4, [5, 6, 7]]

The extend method is like the append method except that it allows us to add one list to another as like

>>> x = [1, 2, 3, 4]
>>> y = [5, 6, 7]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6, 7]

There are also a special insert method to insert new list elements between two existing elements or at the front of the list. Insert is used as a method of lists and takes two additional arguments. The first additional argument is the index position in the list where the new element should be inserted, and the second is the new element itself as like

>>> x = [1, 2, 3]
>>> x.insert(2, "hello")
>>> print(x)
[1, 2, 'hello', 3]
>>> x.insert(0, "start")
>>> print(x)
['start', 1, 2, 'hello', 3]

It is  easiest to think of list.insert(n, elem) as meaning insert elem just before the nth element of list. Insert is just a convenience method. Anything that can be done with insert can also be done with slice assignment. That is list.insert(n, elem) is the same thing as list[n:n] = [elem] when n is non-negative. Using insert makes for somewhat more readable code, and insert even handles negative indices as like

>>> x = [1, 2, 3]
>>> x.insert(-1, "hello")
>>> print(x)
[1, 2, 'hello', 3]

The del statement is the preferred method of deleting list items or slices. It does not do anything that can not be done with slice assignment but it is usually easier to remember and easier to read….

>>> x = ['a', 2, 'c', 7, 9, 11]
>>> del x[1]
>>> x
['a', 'c', 7, 9, 11]
>>> del x[:2]
>>> x
[7, 9, 11]

 

In general del list[n] does the same thing as list[n:n+1] = [], whereas del list[m:n] does the same thing as list[m:n] = [].

The remove method is not the converse of insert. Whereas insert inserts an element at a specified location  remove looks for the first instance of a given value in a list and removes that value from the list…

>>> x = [1, 2, 3, 4, 3, 5]
>>> x.remove(3)
>>> x
[1, 2, 4, 3, 5]
>>> x.remove(3)
>>> x
[1, 2, 4, 5]
>>> x.remove(3)
Traceback (innermost last):
 File "<stdin>", line 1, in ?
ValueError: list.remove(x): x not in list

If remove can not find anything to remove, it raises an error. we can catch this error by using the exception-handling abilities of Python or we can avoid the problem by using in to check for the presence of something in a list before attempting to remove it.

The reverse method is a more specialized list modification method. It efficiently reverses a list in place.

>>> x = [1, 3, 5, 6, 7]
>>> x.reverse()
>>> x
[7, 6, 5, 3, 1]

Sorting List in Python-: Lists can be sorted by using the built-in Python sort method as like

>>> x = [3, 8, 4, 0, 2, 1]
>>> x.sort()
>>> x
[0, 1, 2, 3, 4, 8]

This method does an in-place sort that is changes the list being sorted. To sort a list without changing the original list we have two options. we can use the sorted() built-in function or we can make a copy of the list and sort the copy as like

>> x = [2, 4, 1, 3]
>>> y = x[:]
>>> y.sort()
>>> y
[1, 2, 3, 4]
>>> x
[2, 4, 1, 3]

Sorting works with strings as like

>> x = ["Life", "Is", "Enchanting"]
>>> x.sort()
>>> x
['Enchanting', 'Is', 'Life']

The sort method can sort just do anything because Python can compare just about anything. But there are one caveat in sorting. The default key method used by sort requires all items in the list to be of comparable types. That means that using the sort method on a list containing both numbers and strings raises an exception:

>> x = [1, 2, 'hello', 3]
>>> x.sort()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'

we can sort a list of lists as like

>> x = [[3, 5], [2, 9], [2, 3], [4, 1], [3, 2]]
>>> x.sort()
>>> x
[[2, 3], [2, 9], [3, 2], [3, 5], [4, 1]]

According to the built-in Python rules for comparing complex objects the sublists are sorted first by ascending first element and then by ascending second element.

sort is even more flexible it has an optional reverse parameter that causes the sort to be in reverse order when reverse=True and it is  possible to use our own key function to determine how elements of a list are sorted.

Custom Sorting-: To use custom sorting we need to be able to define functions.Sort uses built-in Python comparison functions to determine ordering which is satisfactory for most purposes. we want to sort a list in a way that does not  correspond to this default ordering. Suppose that we want to sort a list of words by the number of characters in each word, as opposed to the lexicographic sort that Python normally carries out.

To do this write a function that returns the value, or key, that we want to sort on and use it with the sort method. That function in the context of sort is a function that takes one argument and returns the key or value that the sort function is to use.

For number-of-characters ordering a suitable key function could be

def compare_num_of_chars(string1):
return len(string1)

This key function is trivial. It passes the length of each string back to the sort method rather than the strings themselves.

After we define the key function using it is a matter of passing it to the sort method by using the key keyword. Because functions are Python objects they can be passed around like any other Python objects. Here are a small program that illustrates the difference between a default sort and our custom sort as like

>> def compare_num_of_chars(string1):
... return len(string1)
>>> word_list = ['Python', 'is', 'better', 'than', 'C']
>>> word_list.sort()
>>> print(word_list)
['C', 'Python', 'better', 'is', 'than']
>>> word_list = ['Python', 'is', 'better', 'than', 'C']
>>> word_list.sort(key=compare_num_of_chars)
>>> print(word_list)
['C', 'is', 'than', 'Python', 'better']

The first list is in lexicographical order (with uppercase coming before lowercase), and the second list is ordered by ascending number of characters.

Custom sorting is very useful but if performance is critical it may be slower than the default. Normally  this effect is minimal but if the key function is particularly complex the effect may be more than desired, especially for sorts involving hundreds of thousands or millions of elements.

One particular place to avoid custom sorts is where we want to sort a list in descending rather than ascending order. In this case we use the sort method’s reverse parameter set to True. If for some reason we do not want to do that, it’s still better to sort the list normally and then use the reverse method to invert the order of the resulting list. These two operations together the standard sort and the reverse will still be much faster than a custom sort.

The sorted() function-: Lists have a built-in method to sort themselves such as the keys of a dictionary don’t have a sort method. Python also has the built-in function sorted(), which returns a sorted list from any iterable. sorted() uses the same key and reverse parameters as the sort method as like

>> x = (4, 3, 1, 2)
>>> y = sorted(x)
>>> y
[1, 2, 3, 4]
>>> z = sorted(x, reverse=True)
>>> z
[4, 3, 2, 1]

Suppose that we have a list in which each element is in turn a list: [[1, 2, 3], [2, 1, 3], [4, 0, 1]]. If we wanted to sort this list by the second element in each list so that the result would be [[4, 0, 1], [2, 1, 3], [1, 2, 3]], what function would we write to pass as the key value to the sort() method?

Nested List and Deep Copies -: Lists can be nested. One application of nesting is to represent two-dimensional matrices. The members of these matrices can be referred to by using two-dimensional indices. Indices for these matrices work as like …

>>> m = [[0, 1, 2], [10, 11, 12], [20, 21, 22]]
>>> m[0]
[0, 1, 2]
>>> m[0][1]
1
>>> m[2]
[20, 21, 22]
>>> m[2][2]
22

This mechanism scales to higher dimensions in the manner We would expect.We need to concern yourself with. But we may run into an issue with nested lists, specifically the way that variables refer to objects and how some objects (such as lists) can be modified (are mutable). An example is the best way is as like..

>>> nested = [0]
>>> original = [nested, 1]
>>> original
[[0], 1]

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *