We have learned to use numbers and strings in Python. Now let us learn about lists.
- A list is a compound data type in Python used to group data together. It is a sequence of comma separated values written in square brackets where each element of the sequence is assigned an index. The first index is 0.
- The data type of the elements in the list need not be of the same type. This means that you can have a number and a string grouped in the same list.
- To access the elements of the list ,we use the index of the elements in the list .We can also slice the main list in the following way. We can use a:b or a: or :b (a and b are list indices) in the square bracket to slice the list and get a new list from index a to index b ,from index a to end index and from start index to index b respectively.
- Remember python list indices start from 0. So the first index is always 0.
- Adding new values to a list: We can use “append” function or we can directly assign values to particular indices (or change values).
- To change the values in the list, we use the “=” operator. Lists are mutable. It means that elements in a list can be changed.
2. To add values to a list ,we use append(data).
I will teach you about iterating in a list to access each element later. That will be covered in the loops blog.
- To delete a list value, we use the del( ) operator.
- Operations that we earlier used on strings can also be used on lists. So we can use len(list) to get the length of the list, we can add 2 lists or concatenate them, etc.
- The “in” construct can be used to check if any element is in the list. It returns true or false.
- Common list methods are as follows. I have also shown how they can be used.
- list.append(elem) — adds a single element to the end of the list.
- list.insert(index, elem) — inserts the element at the given index, shifting elements to the right.
- list.extend( list 2) adds the elements in list 2 to the end of the list.
- list.count(x) returns the number of times x appears in the list.
- list.copy( ) return a shallow copy of the list. Equivalent to a[:].
- list.index(elem) — searches for the given element from the start of the list and returns its index.
- list.remove(elem) — searches for the first instance of the given element and removes it .
- list.sort() — sorts the list in place (does not return it).
- list.reverse() — reverses the list in place.
- list.pop(index) — removes and returns the element at the given index.
Check out the following operations and try them on your own with your own lists.
- A list can contain other lists in itself.