Python List Operation

来源:互联网 发布:淘宝宝贝卖点词 编辑:程序博客网 时间:2024/05/16 10:12

Python List Examples – Insert, Append, Length, Index, Remove, Pop

Tweet

Lists in Python language can be compared to arrays in Java but they are different in many other aspects. Lists are used in almost every program written in Python. In this tutorial we will understand Python lists through practical examples.

We will cover the following in this article :

  • How to define a list
  • How to add elements to a list
  • How access sub lists
  • How to search within lists
  • How to delete elements from a list
  • Operators and lists

1. Create a Python List

Defining a List in Python is easy. You just need to provide name of the list and initialize it with values. Following is an example of a List in Python :

>>> myList = ["The", "earth", "revolves", "around", "sun"]>>> myList['The', 'earth', 'revolves', 'around', 'sun']

So you can see that a list named ‘myList’ was created with some elements.

Lists in python are zero indexed. This means, you can access individual elements in a list just as you would do in an array. Here is an example :

>>> myList[0]'The'>>> myList[4]'sun'

Lists cannot be accessed beyond the rightmost index boundary. Here is an example :

>>> myList[5]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

So we see that when we tried to access myList index 5, an error was thrown saying that this index is out of range.

But, on the other hand, if you try to access value at a negative index then values from the rightmost index can be accessed backwards. Here is an example:

>>> myList[-1]'sun'

So we see that index -1 was translated into index ‘4’ and corresponding value was produced in output.

If you are new to Python, you should start by writing a Python hello world program, and understanding Python variables and strings.

2. Add Elements to a List

One can use the method insert, append and extend to add elements to a List.

The insert method expects an index and the value to be inserted. Here is an example of insert :

>>> myList.insert(0,"Yes")>>> myList['Yes', 'The', 'earth', 'revolves', 'around', 'sun']

So we see the value ‘yes’ was inserted at the index 0 in the list and all the other elements were shifted accordingly.

The append method can take one or more elements as input and appends them into the list. Here is an example :

>>> myList.append(["a", "true"])>>> myList['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true']]

So, the two values were appended towards the end of the list. Note that whether we add one element or multiple elements to the list, if we have used append then they will be added as a single element only. This can be proven if we try to check the length of myList now :

>>> len(myList)7

So we see that though we added two elements but they are counted as a single element (or a sub-list) in myList.

The other method that can be used to add elements to list is extend. Like append, it also expects one or more values as input. But, unlike append, all the elements are added as individual elements. Here is an example :

>>> myList.extend(["statement", "for", "sure"])>>> myList['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']>>> len(myList)10

So we see that each element got added as a separate element towards the end of the list.

3. Slice Elements from a List

Python also allows slicing of the lists. You can access a part of complete list by using index range. There are various ways through which this can be done. Here are some examples :

If it is required to access a sub-list from index 1 to index 3 then it can be done in following way:

>>> myList[1:4]['The', 'earth', 'revolves']

Note that the index 4 was passed instead of 3 because if we pass index range x:y then values up to index y-1 are printed.

Now, if it is required to access first ‘n’ elements of the list, then there is no need to provide index ‘0’, only the value of ‘n’ is required. Here is an example :

>>> myList[:4]['Yes', 'The', 'earth', 'revolves']

So we see that first three elements were accessed.

Similarly, if last ‘n’ elements are required to be accessed then only starting index is required. Here is an example :

>>> myList[4:]['around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']

So we see that all the elements beginning from index 4 till end of the list were displayed.

If neither starting index, nor the ending index is provided then complete list is displayed. Here is an example :

>>> myList[:]['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']

4. Search the Lists and find Elements

Lists can easily be searched for values using the index method that expects a value that is to be searched. The output is the index at which the value is kept.

Here is an example :

Here we try to search the list for value ‘revolves’.

>>> myList.index("revolves")3

So we see that the corresponding index was displayed in the output.

If some value is not found then an error is displayed. Here is an example :

>>> myList.index("a")Traceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: 'a' is not in list

Here is how you can search a sub list :

>>> myList.index(["a", "true"])6

If it is desired to just whether an element is present in a list, it can be done in following way :

>>> "sun" in myListTrue

So we see that ‘True’ was returned as ‘sun’ was present in the list.

5. Delete Elements from the List

Python provides the remove method through which we can delete elements from a list. It expects the value which is required to be deleted.

Here are some examples :

>>> myList['Yes', 'The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("Yes")>>> myList['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'statement', 'for', 'sure']
>>> myList.remove("statement")>>> myList['The', 'earth', 'revolves', 'around', 'sun', ['a', 'true'], 'for', 'sure']

Here we see that remove can be used to easily delete elements in list.

Here is how a sub list can be deleted :

>>> myList.remove(["a", "true"])>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure']

So we see that the sub list was deleted from the original list.

If it is required to access the last element and then to delete it, this can be done through pop method.

>>> myList.pop()'sure'>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for']

So we see that the value was displayed and  deleted simultaneously.

6. Python List Operators

Python allows to use mathematical operators like +, * etc to be used with lists.

Here are some examples :

>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for']
>>> myList = myList + ["sure"]>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure']
>>> myList += ["."]>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']
>>> myList *= 2>>> myList['The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.', 'The', 'earth', 'revolves', 'around', 'sun', 'for', 'sure', '.']

So we see that through + operator elements could be added to the list and through * operator we can add the complete list repeatedly towards the end.

0 0
原创粉丝点击