Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Understanding Lists in Python

In this article we will talk about the lists in Python, an interactive, object-oriented, extensible programming language.

The Python language has many compound data structure. Sequence is the most basic data structure available in Python. A sequence is a data structure which can hold multiple values either of same type or different types. Every value or item of the sequence is assigned a number which represent its position or index.

Sequence has six built in types in Python. There are some operations which can be applied on every sequence types. These includes adding, multiplying, slicing, indexing and checking for membership, finding the length of sequence and for finding the smallest and largest elements.

A list in Python is an excellent method for storing arrays of objects. Unlike the arrays in C++ or Java, the items stored in Lists can be of different data types. Basically, a list is an ordered collection of arbitrarily typed objects without having any fix size. A list can be used very efficiently to represent the arbitrary collections such as emails in your in box, employees in an organization or list of files stored in a folder and so on.

List Values

You can create a list using various methods. The simplest method is to enclose the elements in square brackets [ ]:

zs = ["hello", 2.0, 5, [10, 20]]

The above example is a list contains an integer, a float, a string and another list too. This list within a list is called nested list. A list is said to be empty if it has no elements and is denoted []. We can understand this using the code given below:

Listing 1: Creation f List

 >>>vocabulary = ["apple", "cheese", "dog"]
 >>>numbers = [17, 123]
 >>>an_empty_list = []
 >>>print(vocabulary, numbers, an_empty_list)
 ["apple", "cheese", "dog"]  [17, 123]  []

Accessing the Elements

To access the elements stored in a list, one should provide the index value of that particular element. It is just like we access elements if an array in C. Always remember that starting index number will be always zero. This as a simple example:

Listing 2: Accessing the list elements

>>list1 = [‘physics’,’Biology’,2010,1013]
>>list2 = [1,2,3,4,5,6]
>>print”List1[0]”,list1[0]
>>print”List2[1-5]”,list2[1:5]

When we execute this code, we get following as the output:

List1[0]: Physics
List2[1-5]: [2,3,4,5]

We can use any expression evaluating an integer as an index:

Listing 3: Use of expression

>>> numbers[9-8]
5
>>> numbers[1.0]			#Produce an error when index value is not integer
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: list indices must be integers, not float

We can use a loop as a list index.

Listing 4: Use of a loop

>>testlist = ["war", "famine", "pestilence", "death"]
>>for i in [0, 1, 2, 3]:
print(testlist[i])

In this example, each time through the loop, variable I is used as an index and I ’th element will be printed. This method is called list traversal.

Sequence Operations

List supports all the sequence operations. To show you, how these operations work, check these examples in your Python Interpreter, most probably Python IDLE:

Listing 5: Length function

>>> L = [123, 'spam', 1.23]			  # A list of three different-type objects
>>> len(L)  					  # Number of items in the list
3						 # Output the length of the list

In above example, using built in len() function, we find the length of the list L is 3. There are some more examples to understand the working of the list. These operations are slicing, concatenate and repeat. These operations create a new list from an older one without changing the original elements:

Listing 6: Some other operations

>>> M = [123, 'mail', 5.7] 			  # A list of three different-type objects
>>> M[:-1] 					  # Slicing a list returns a new list
[123, 'mail']
>>> LM+ [4, 5, 6]  				  # Concat/repeat make new lists too
[123, 'mail', 5.7, 4, 5, 6]
>>> M * 2

[123, 'mail', 5.7, 123, 'spam', 1.23]
>>> M  					 # We're not changing the original list
[123, 'spam', 5.7]

Type-Specific Operations

List of Python can look similar to the Arrays to other programing languages but they are totally different in behaviour. The major difference and also the advantage of lists is that there are not fixed type constraints for the elements. List can contain totally different items as we looked in Listing 6 where we used an integer, a string and a floating point number as list elements. One more advantage over traditional arrays is that lists don’t have any fixed size. They can expend or shrink as the list-specific operation demands.

Listing 7: Type-specific operations

>>> M.append('NI')				  # Growing: add object at end of list
>>> M
[123, 'mail', 5.7, 'NI']
>>> M.pop(2) 					 # Shrinking: delete an item in the middle
5.7
>>>M 						 # "del L[2]" deletes from a list too
[123, 'mail', 'NI']

In above example, append method insert an item at the end of the list. The pop method then deletes an item at a given index. These two methods shows the expansion and shrinking of the list. Some other list operations works same as insert(): insert an item at a given index, remove(): removes an item, extend() : insert multiple items at the end of the list. We can change the position of list objects using some other list methods. This property is called mutability.

Listing 8: Some other list methods

>>> N = ['bb', 'aa', 'cc']
>>> N.sort()
>>> N
['aa', 'bb', 'cc']
>>>N.reverse()
>>> N
['cc', 'bb', 'aa']

Nesting of Lists

Python provides a very good feature in its core data types is the support of arbitrary nesting- we can nest the data types within each other as we like. For example, a list can have a dictionary which may have another list nested inside it and so on. One application of this feature in Python is representation of matrixes or “multidimensional arrays”. A multidimensional array is a list with nested lists:

Listing 9: Multidimensional Array

>>> M = [[1, 2, 3], 			 # A 3 × 3 matrix, as nested lists
[4, 5, 6], 				 # Code can span lines if bracketed
[7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

Here we’ve build a 3x3 matrix of numbers using a list that contains three other lists. We can access this matrix using various methods such as:

Listing 10: Access the elements of the matrix

>>> M[1]  					 # Get row 2
[4, 5, 6]
>>> M[1][2] 					 # Get row 2, then get item 3 within the row
6

The first operation is fetching the entire second row here where the second operation is fetching the third item within that row.

Some examples of the list methods

Now as we are about to finish our topic list, let's have a look on some list operations to understand the working of list more clearly:

Listing 11: Multiple operation on list

>>> mylist = []
>>> mylist.append(5)
>>> mylist.append(27)
>>> mylist.append(3)
>>> mylist.append(12)
>>> mylist
[5, 27, 3, 12] 	
>>> mylist.insert(1, 12) 			# Insert 12 at pos 1, shift other items up
>>> mylist
[5, 12, 27, 3, 12]
>>> mylist.count(12) 				# How many times is 12 in mylist?
2
>>> mylist.extend([5, 9, 5, 11]) 		# Put whole list onto end of mylist
>>> mylist
[5, 12, 27, 3, 12, 5, 9, 5, 11])
>>> mylist.index(9) 				# Find index of first 9 in mylist
6
>>> mylist.reverse()
>>> mylist
[11, 5, 9, 5, 12, 3, 27, 12, 5]
>>> mylist.sort()
>>> mylist
[3, 5, 5, 5, 9, 11, 12, 12, 27]
>>> mylist.remove(12)			 # Remove the first 12 in the list
>>> mylist
[3, 5, 5, 5, 9, 11, 12, 27]

Conclusion

Lists are one of the most important data types defined in Python. Its ability to handle complex data structure makes it programmer’s choice of use where tables or matrix like data structure is needed. Because, unlike the arrays of C or C++, the size of the list is not fixed, it is very useful where user have to make changes at runtime. Its ability to store multiple data types gives it an edge over other programming language’s similar data types.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login