Close container

...with new Python Tips and Tricks
in every couple of weeks


Comprehensive study of Python Lists

Posted on May 30, 2021 By Pawan Jain basics python

In this tutorial you will understand how python lists works, how to do various operations like remove, add, sort elements, slicing, indexing with Python lists
Detailed analysis of Python Lists

In the previous article, we've learned about different types of variables to store data in Python, including string, float, integer and Boolean. But suppose that if we have a lot of data, For example, names of all new students enrolling in a class.

So far, our definition of a variable allows us only to represent a single piece of data. Therefore, if we wanted to describe a group of new students' names enrolled in our class, we have to define each of them separately like this:

>>> student1 = 'Michael' >>> student2 = 'Smith' >>> student3 = 'Roy'

Further, Every time we get a new student enrolled in our class, we need to create a new string variable (student4, student5, ...) to represent that student's name. This becomes cumbersome if we have hundreds of such variables mapping each of enrollment to a new string aka student here.

To overcome this situation, Python has lots of easy, fast, and efficient way to deal with all kinds of data collections. Rather than using exclusively named variables to represent a group of related data, most programming languages allow us to illustrate this type of data using a single name and call them a dynamic array. In Python, it is called a list.

A list is any comprised of multiple data items, separated by commas, inside square brackets. Typically, we assign a name to the list using an = character, just as we would with variables. For the above example, we can define a list of "students" like this.

>>> students = ["Michael", "Smith", "Roy"] >>> print(students) ["Michael", "Smith", "Roy"]

Note: We can print the python list simply by passing the variable in the in-built function print() as shown in the code above.

Definition: A list is a value that contains multiple values in an ordered sequence. A list is a mutable sequence that is typically a collection of homogeneous items. The term Mutable refers to the property that one can change a list after its creation. And the ability to change values in a list for other values is called mutability

Accessing list items by position

Each item in a list has a position number, starting with 0, even though you don't see any numbers. You can refer to any item in the list by its number using the name for the list followed by a number in square brackets in the following way.

>>> students = ["Michael", "Smith", "Roy"] >>> students[0] 'Michael' >>> students[2] 'Roy'

Note: Since the first index is 0, the last index is less than the list's total size. For here, a list of four items has three as its last index.

Few points to note

  • You will get a TypeError error if the Indexes are not integer values
  • On the other hand, if we use an index that exceeds the number of values in your list value Python will give us an IndexError error message
  • While indexes start at 0 and go up, we can also use negative integers. The value -1 refers to the last index in a list, and similarly the value -2 refers to the penultimate index in a list.

Adding Elements to a List

If we might want to add a new element to a list for many reasons. For example, we want to add a late admitted student to our class. There are three list methods that you can use to add elements to a list. They are as follows:

  • append()
  • extend()
  • insert()

1. Using append()

We can use either a literal or variable name inside the quotation marks to add the element to the list.

For example in our existing class of three students, the line students.append("Lara") adds the name Lara to the list. And in the same way the line students.append(new_student) adds whatever name is stored in the new_student variable to the list.

>>> students.append("Lara") # or by passing a stored variable >>> new_student = "Lara"] >>> students.append(new_student) >>> print(students) ["Michael", "Smith", "Roy", "Lara"]

Notice that when we append an item to a list, the new element is added to the end of the list, as our new student Lara appended at the end of the list

2. By Using insert()

We can add a new element at any position in our list by using the insert() method. We do this by specifying the value of the new item and the index of the new element.

In this example, the code inserts the value 'Lara' at the beginning of the list. The insert() method opens space at position 0 and stores the value 'Lara' at that location. This operation shifts other values in the list one place to the right in this way:

>>> students = ["Michael", "Smith", "Roy"] >>> students.append("Lara", 0) ["Lara", "Michael", "Smith", "Roy"]

Note: If the value for the index parameter of insert() is larger than the greatest index in the list, the value is inserted at the end of the list:

>>> students.insert(10, "Lara") ["Michael", "Smith", "Roy", "Lara"]

Note: When you insert() an item into a list, you do not need to assign the result to the original list. For example, the following code actually erases the colors list, for the same reason insert() is said to alter colors in place:

>>> students = students.insert(-1, "Lara") >>> print(colors) None

3. By Using extend()

The extend() method is used to add several new elements to the end of a list.

It takes a single parameter that must be an iterable type. The elements of iterable are appended to list in the same order that they appear in the argument passed to .extend(). Suppose we want to add two new students to our class simultaneously, we can do so in the following way.

>>> students.append("Lara") # or by passing a stored variable >>> new_student = "Lara"] >>> students.append(new_student) >>> print(students) ["Michael", "Smith", "Roy", "Lara"]

Changing an item in a list

You can change an item in a list using the = assignment operator just like you do with variables. Make sure you include the index number in square brackets to indicate which item you want to change.

For example, in our class of four students, suppose we feed the student name "Smithh" instead of "Smith" in the students' list. We can correct it now quickly as follows.

>>> students = ["Michael", "Smithh", "Roy"] >>> students[1] = "Smith" >>> print(students) ["Michael", "Smith", "Roy"]

Note: You can change the value of any item in a list

Removing Values from Lists

Often, we want to remove an item or a set of items from a list. For instance, suppose a student unenroll from the course later. We can remove an element from lists in these ways.

1. Removing an Item by Value (.remove)

Sometimes we won't know the position of the value we want to remove from a list, there python remove() method comes in picture. If you only know the value of the item we wish to remove, we should use the remove() method.

For example, let's say we want to remove the value 'Roy' from the list of students.

>>> students = ["Michael", "Smithh", "Roy", "Lara"] >>> students.remove('Roy') >>> print(students) ["Michael", "Smithh", "Lara"]

Note: The remove() method deletes only the first appearance of the value. If there's a possibility the same value seems more than once in the list, we'll need to use a loop to remove all such occurrences.

Attempting to delete a value that doesn't appear in the list will result in a ValueError error as shown below

>>> students = ["Michael", "Smithh", "Sam", "Lara"] >>> students.remove('Roy') Traceback (most recent call last): File "", line 1, in ValueError: list.remove(x): x not in list

2. Removing all elements in the list (.clear)

We can use clear() to remove everything from the list. After calling clear(), the same list will be emptied. This can be helpful when you have completed working on the items in the list, and we need to begin over from scratch—for example, creating a new class of students in the next academic year.

# By Using clear >>> students.clear() # Creating new empty list again >>> students = []

3. Remove element using index (.pop)

Sometimes we'll want to use the value of an item after you remove it from a list. The pop() method removes the last thing in a list, but it lets you work with that item after removing it.

Calling pop() without an argument, like in the example below, will default to removing the last item in the list and returning it. The term pop comes from thinking of a list as a stack of things and popping one item off the top of the stack. In this analogy, the top of a stack corresponds to the end of a list.

>>> students = ["Michael", "Smith", "Sam"] >>> firstjoiner = students.pop(0) >>> print(firstjoiner) 'Michael' # default, pop last element of list >>> students.pop() 'Sam' >>>print(students) ["Michael", "Smith"]

Unlike .insert(), Python raises an IndexError if you pass to .pop() an argument larger than the last index:

Sorting a List

We can use the built-in sort() method to sort a list in place or use Python's sorted() function to return a new sorted list.

A common misconception with Python is that if you call sort(), you can assign the now-sorted list to a variable. However, you will see that sort() doesn't return the sorted list when you do that. It always returns None.

>>> students = ["Michael", "Smith", "Sam", "Lara"] >>> sortedlist = students.sort() >>> print(sortedlist) None # Correct way >>> students.sort() >>> print(students) ['Lara', 'Michael', 'Sam', 'Smith']

We can also pass the keyword "reverse" to the sort() to sort the values in reverse order. By default, the sort() method sort the list in ascending order.

>>> students.sort(reverse=True) ['Smith', 'Sam','Michael','Lara']

The sort() in Python uses "ASCIIbetical order" rather than actual alphabetical order to sort strings implies uppercase letters come before lowercase letters.

>>> ['Anthony', 'ana','Smith', 'sam']

Finding the index of element in the python list

Python offers a index() method that returns a number indicating the position of an item in a list based on the index number. If the value isn't in the list, then Python produces a ValueError error.

For example, we want the roll number of "Smith" from our students' list. We can quickly call the .index() method to obtain that.

>>> students = ['Smith', 'Sam','Michael'] >>> students.index("Smith") 0

Note: the indexing start from 0

Note: When there are duplicates of the value in the list, the method return index of its first appearance.

Slicing in python list

We see how we can get a single value from a list by the index method. In the same way, a slice can get different values from a list in the form of a new list. Slicing a list is done using square brackets and entering a start and stop value separated by a colon.

>>> students[0:2] >>> students[1:2]

Note. In Slicing of the list contain values from the starting index to the stop index, and exclusing the stop index

Omitting the end index and providing only the start index will slice everything from the start to the end of the list and vice versa

>>> students = ["Michael", "Smith", "Sam"] # omitting starting index (take 0 as default) >>> students[:1] ["Michael", "Smith" # similarly omitting ending index >> students [:] ["Michael", "Smith", "Sam"]

Conclusion

In this article you learned what lists are and how to work with the individual items in a list. You learned how to define a list and how to add and remove elements by different techniques. You learned to sort lists permanently and temporarily for display purposes. You also learned how to find the index of an item in the list, how to do slicing and how to avoid index errors when you’re working with lists.