<

[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x

Lists in Python

Published on
3,850 Points
650 Views
2 Endorsements
Last Modified:
Introduction of Lists in Python:
There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can also say like the place holder where a number of elements can be stored in a given order. 

We can use lists for indexing , adding , multiplying or checking for the member of that sequence. We can also check the lenght by identifying the minimum and maximum elements present in the lists. 

Lists are called as the compound data types of Python. The lists are separated by commas and enclosed by square brackets i.e. [].
Lists are very similar to arrays in C programming language but the difference is that Python lists can be of different data types.
 
Slice operators are used to access the values from a list for example ( [] ] OR [] : ] ) . The indexes starts with zero i.e. "0" from beginning and if we starts the index from
the end then it starts with negative one i.e. "-1" . We can use a plus sign (+) for concatenate a list and an asterisk sign (*) to repeat the list.
 
Let's try to see how a simple list can look like :

 
login as: sloba
sloba@*********'s password:
Welcome to Linux Mint 17.2 Rafaela (GNU/Linux 3.16.0-38-generic x86_64)

Welcome to Linux Mint
 * Documentation:  http://www.linuxmint.com
Last login: Mon Jul 13 14:18:53 2015 from 172.27.66.246
sloba@sloba-VirtualBox ~ $ python
Python 2.7.10 (default, Jul 13 2015, 14:15:32)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list =[1,2,3,4]
>>> list
[1, 2, 3, 4]
>>>

Open in new window


We can print the values by just typing the variable that was declared to create a list or we can use the print option to display the values as shown below:
>>> print list
[1, 2, 3, 4]
>>>
>>>

Open in new window

Let's see an example to have a list having different data types :
 
sloba@sloba-VirtualBox ~ $ python
Python 2.7.10 (default, Jul 13 2015, 14:15:32)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 2,A,B]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
>>>

Open in new window


If we are using different data types then we should use a string within single quotes else we can end up with an error as above . So let’s try with some proper defined values within a list.
 
sloba@sloba-VirtualBox ~ $ python
Python 2.7.10 (default, Jul 13 2015, 14:15:32)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 2,A,B]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'A' is not defined
>>>
>>> list1 = [1, 2,'A','B']
>>> list1
[1, 2, 'A', 'B']
>>>

Open in new window

 
Now let's see how we can use concatenation of lists in Python with an example, from the above we have defined two lists such as "list" which
is only having numbers and "list1" which is having numbers and strings.
 
>>> list
[1, 2, 3, 4]
>>> list1
[1, 2, 'A', 'B']
>>> list + list1
[1, 2, 3, 4, 1, 2, 'A', 'B']
>>>

Open in new window


From the above example we can see that the plus symbol helps us to concatenate two different lists having different data types to join and display or print all the values.
 
If we want to see certain values from the list we can use the index and list it out.
For example if we have the list called "indexlist" and having values like []1,2,3,'AA','BB', 4].
And we want to pull the values starting from third value till end then we have to execute the something like below :
>>> indexlist
[1, 2, 3, 'AA', 'BB', 4]
>>>
>>> indexlist[2:]
[3, 'AA', 'BB', 4]

Open in new window


Now say we want the values starting from second till fourth value then we have to execute the something like below:
>>> indexlist[1:4]
[2, 3, 'AA']

Open in new window

We are getting "AA" as the fourth values because the index starts from "0" i.e. zero.

>>> indexlist[0]
1
>>>

Open in new window


Now if we want the values to be pulled from end till first then we have to write as shown in below exmaple :
>>> reversedlist =  indexlist[::-1]
>>> reversedlist
[4, 'BB', 'AA', 3, 2, 1]

Open in new window


Another method to achieve the above list using a for loop as shown below :
>>> reversedlist
[4, 'BB', 'AA', 3, 2, 1]
>>> reversedlist.reverse()
>>> for i in reversedlist : print i
...
1
2
3
AA
BB
4

Open in new window

Now let's see if we want to repeat the values two times .

>>> a =[1,2]
>>> a
[1, 2]
>>> a *2
[1, 2, 1, 2]

Open in new window


Updating list in Python :
We can update single or multiple values of the lists by using slice on the assignment operators.
Here is a very simple example for updating a existing lists:
 
>>> a =[1,2,3]
>>> a
[1, 2, 3]
>>> a[0]
1

Open in new window

We see the starting value [index starting from 0 ] of the list "a" is one i.e. "1" , now let us update to four i.e. '4'

>>> a
[1, 2, 3]
>>> a[0] =4
>>> a
[4, 2, 3]
>>>

Open in new window


We can also add values to existing lists for example we have a list called "a" now lets add "5" as value to the list . 
 
>>> a
[4, 2, 3]
>>> a.append(5)
>>> a
[4, 2, 3, 5]
>>>

Open in new window

 
If we want to add within the list like to add multiple values to the list then we have to use extend not append [Append is only used for adding single value to a list].
For example :  
>>> list
['A', 'B', 'C']
>>> list.extend(['D','E'])
>>> list
['A', 'B', 'C', 'D', 'E']
>>>

Open in new window


If add a values in between a list by using insert function but note insert is used to insert only single value to an existing list.  
 
>>> list
['A', 'B', 'C', 'D', 'E']
>>> list.insert(1,"insert")
>>> list
['A', 'insert', 'B', 'C', 'D', 'E']
>>>

Open in new window


Delete elements from List:
To delete an element from a list can used by using a function remove. 
>>> list
['A', 'insert', 'B', 'C', 'D', 'E']
>>> list.remove("insert")
>>> list
['A', 'B', 'C', 'D', 'E']
>>>

Open in new window


From the above example we can see that we have to pass the value which we want to remove from the list. 

>>> list
['A', 'B', 'C', 'D', 'E']
>>>
>>>
>>> list.append('A')
>>> list
['A', 'B', 'C', 'D', 'E', 'A']
>>> list.remove("A")
>>> list
['B', 'C', 'D', 'E', 'A']
>>>

Open in new window


The above example shows that we have two identical value i.e. "A" and when we use remove , we could see the first occurrence is removed not the second one.
If we want to remove the last element from the list then we can also make use of "pop" .
 
>>> list
['B', 'C', 'D', 'E', 'A']
>>> list.pop()
'A'
>>> list
['B', 'C', 'D', 'E']
>>>

Open in new window

​ From the above we see that this removes the last element but also return the value which was removed from the list.

Length of list :
We can also check the length of the list . For example: 
>>> list =['A', 'B', 'C', 'D', 'E']
>>> list
['A', 'B', 'C', 'D', 'E']
>>> len(list)
5
>>>

Open in new window


So there are five elements or values in our list which defined as shown in above example. If we want to count the number of times the element is repeated then we can use something like
below:
 
>>> list
['A', 'B', 'C', 'D', 'E']
>>> list.count('A')
1
>>>

Open in new window


To see the elements in reverse we can call "reverse" after the list as shown in below example :
 
>>> list
['A', 'B', 'C', 'D', 'E']
>>> list.reverse()
>>> list
['E', 'D', 'C', 'B', 'A']
>>>

Open in new window


From the above examples and details we will be able to use Python list to add and remove the elements from the sequence. 
To know more about lists in Python can found from python.org the official website for Python language. 

Thank you for reading my article. Please feel free to leave me some feedback or to suggest any future topics. 
Please 'Vote this article as helpful' if you liked on the bug green button at the bottom of this article.

Looking forward to hear from you - Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )
 
2
Comment
Author:Swadhin Ray
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
0 Comments

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Join & Write a Comment

Suggested Articles

Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month