The python lists are containers that are used to store a list of values of any type. Unlike other variables Python lists are mutable i.e., you can change the elements of a list in place; Python will not create a fresh list when you make changes to an element of a list. List is a type of sequence like strings and tuples but it differs from them in the way that lists are mutable but strings and tuples are immutable.
CREATING AND ACCESSING LISTS
A list is a standard data type of Python that can store a sequence of values belonging to any type. The lists are depicted through square brackets.
[ ] # list with no member, empty list
[1,2,3] # list of integers
[1,2.0,3.5] #list of numbers
[‘a’,’b’,’c’] #list of characters
[‘one’,’two’,’three’] #list of strings
[‘a’,1,5.5,’zero’] #list of mixed value types
The memory address of a list will not change even after you change its values.
Thus to create a list you can write in the form given below:
This construct is known as list display construct.
Consider some more examples:
- The empty list: The empty list is [ ]. It is the list equivalent of 0 or ‘ ‘ and like them it also has truth value as false. You can also create an empty list as:
It will generate an empty list and name that list as L.
- Long lists: If a list contains many elements, then to enter such long lists, you can split it across several lines, like below:
Notice the opening square bracket and closing square brackets appear just in the beginning and end of the list.
- Nested lists: A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.,
L1 is nested list with 4 element: 3, 4, [5, 6] and 7. L1 element is a list [5, 6]. Length of L1 is 4 as it counts [5,6] as one element. Also, as L1 is a list (i.e., [5,6]), which means L1 will give 5 and L1 will give 6.
Creating list from existing sequences
You can also use the built-in list type object to create lists from sequences as per the syntax given below:
Where <sequence> can be any kind of sequence object including strings, tuples, and lists. Python creates the individual elements of the list from the individual elements of passed sequence. If you pass in another list, the list function makes a copy.
Consider the following examples:
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
>>>t=(‘w’, ‘e’, ‘r’, ‘t’, ‘y’)
[‘w’, ‘e’, ‘r’, ‘t’, ‘y’]
You can use this method of creating lists of single characters of single digits via keyboard input. Consider the code below:
>>>l1=list(input(“Enter list elements:”))
Enter list elements:171105
[‘1’, ‘7’, ‘1’, ‘1’, ‘0’, ‘5’]
Notice, this way the data type of all characters entered is string even though we entered digit. To enter a list of integers through keyboard, you can use the method given below:
Most commonly used method to input lists is eval(input()) as shown below:
list=eval(input(“Enter list to be added:”))
print(“List you entered:”,list)
when you execute it, it will work like:
Enter list to be added:17,18,25,16,23,26
List you entered:[17,18,25,16,23,26]
Lists are mutable sequences having a progression of elements. There must be a way to access its individual elements and certainly there is. But before we start accessing individual elements, let us discuss the similarity of lists with strings that will make it very clear to you how individual elements are accessed in lists- the way you access string elements.
SIMILARITY WITH STRINGS
Lists are sequences just like strings that you read before. They also index their individual elements, just like strings do.
Thus, you can access the list elements just like you access a string’s elements e.g., List[i] will give you the element at ith index of the list; List[a:b] will give you elements betwwen indexes a to b-1 and so on.
Put in another words, Lists are similar to strings in following ways:
- Length: function len(L) returns the number of items (count) in the list L.
- Indexing and slicing: L[i] returns the item at index i (the first item has index 0), and L[i:j] returns a new list, containing the objects at indexes between i and j (excluding index j).
- Membership operators: Both ‘in’ and ‘not in’ operators work on Lists just like they work for other sequences. That is, in tells if an element is present in the list or not, and not in does the opposite.
- Concatenation and replication operators + and * : The + operator adds one list to the end of another. The * operator repeats a list.
DIFFERENCE FROM STRINGS
Although lists are similar to strings in many ways, yet there is an important difference in mutability of the two. Strings are not mutable, while lists are.
TRAVERSING A LIST
Traversing a list also means the same and same is the tool for it, i.e., the python loops. That is why sometimes we call traversal as looping over sequence.
The for loop makes it easy to traverse or loop over the items in a list as per following syntax:
for <item> in <list>:
process each item here
The most common operators that you perform with lists include joining lists, replicating lists and slicing lists.
Joining two lists is very easy just like you perform addition literally. The concatenation operator +, when used with two lists, joins two lists.
The + operator when used with lists requires that both the operands must be of list types. You cannot add a number or any other value to a list. For example, following expression will result into error:
List + number
List + complex-number
List + string
Repeating or replicating lists
Like strings, you can use * operator to replicate a list specified number of times.
Slicing the lists
Lists also support slice steps. That is, if you want to extract, not consecutive but every other element of the list, there is a way out the slice steps.
MAKING TRUE COPY OF LIST
Sometimes you need to make a copy of a list and you generally tend to do it using assignment
It will not make b as a duplicate list of a; rather just like Python does, it will make label b to point where label a is pointing to.
It will work as long as we do not modify lists. Now, if you make changes in any of the lists, it will be reflected in other because a and b are like aliases for the same list.
You want both lists to be independent of each other. For this, you should create copy of the list as follows:
There is another way of doing it, i.e., creating the true copy of a list, by using the copy() method. You can use the copy() method as follows:
So, in nutshell, you can create a true copy of a list by using any one of the following three ways:
- By using the list() method.
- By using the copy() method.
- By storing all elements of the list using list slice in its copy.
METHODS IN LISTS
**lst.insert(index,item):To insert a new list item, without replacing any of the existing values, we can use the insert() method. returns no value
thislist = ["apple", "banana", "cherry"] thislist.insert(2, "watermelon") print(thislist)
[‘apple’, ‘banana’, ‘watermelon’, ‘cherry’]
l1=['a','e','u'] l1.insert(-10,'i') print(l1)
[‘i’, ‘a’, ‘e’, ‘u’]
**list.append(item): used to add an element to the end of the list.returns no value
lst=[1,2,3] lst.append(4) print(lst)
[1, 2, 3, 4]
lst=[1,3,5] lst.append([2,4,6]) print(lst)
[1, 3, 5, [2, 4, 6]]
**list.extend(list):append elements from another list to the current list. returns no value
thislist = ["apple", "banana", "cherry"] thistuple = ("kiwi", "orange") thislist.extend(thistuple) print(thislist)
[‘apple’, ‘banana’, ‘cherry’, ‘kiwi’, ‘orange’]
lst=['a','e','i'] lst.extend(['o','u']) print(lst)
[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
**list.remove(value):The remove() method removes the specified item.returns no value
lst=[1,2,3,4,5,6,7] lst.remove(4) print(lst)
[1, 2, 3, 5, 6, 7]
**list.pop(index):used to remove the item from the list.returns the value that is being deleted.
lst=[1,2,3,4,5,6,] s=lst.pop(4) print(s)
lst=[1,2,3,4,5,6,] s=lst.pop() print(s)
if no index is specified it removes and returns last element from the list. it raises an error if the list is empty
del list[index]: removes the element at index
lst=[3,4,5,6,7,8] del lst print(lst)
[3, 4, 5, 6, 7]
lst=[18,17,16,25,23,26] del lst[1:3] print(lst)
[18, 25, 23, 26]
del listname : deletes all the elements and the list object too
lst=['a','e','i','o','u'] del lst print(lst)
NameError Traceback (most recent call last)
Cell In, line 3
2 del lst
—-> 3 print(lst)
NameError: name ‘lst’ is not defined
**list.clear():this method removes all the items in the list and makes the list empty
lst=['a','e','i','o','u'] lst.clear() print(lst)
**list.sort(reverse=True/False):sorts the items of the list by default in increasing order. this is done in place and it doesn’t create a new list
lst=['vinny','sasi','anand','chinna'] lst.sort() print(lst)
[‘anand’, ‘chinna’, ‘sasi’, ‘vinny’]
lst=['vinny','sasi','anand','chinna'] T=lst.sort() print(T)
**list.reverse():reverses the current order of elements.this is done in place
lst=[1,3,5,'a','v'] lst.reverse() print(lst)
[‘v’, ‘a’, 5, 3, 1]
**list=list1.copy():makes a true copy of a list
lst=[25,50,75,100,125,150] lst2=lst.copy() print(lst2)
[ 25 , 50 , 75 , 100 , 125 , 150 ]
**list.index(item):returns the index of first matched item from the list.raises error if item is not in list.
**sorted(seq,reverse=True/False):it creates a new list containing the sorted version of list passed.it can take any iterable sequence type and returns a sorted “list.”
val=(1,2,35,4,52,6) sval=sorted(val) print(sval)
[1, 2, 4, 6, 35, 52]
val=['cat','ant','rat','rock','cake'] sval=sorted(val,reverse=True) print(sval)
[‘rock’, ‘rat’, ‘cat’, ‘cake’, ‘ant’]