List in Python
- List in Python is like ArrayList in Java.
- The elements are addressed by index which starts from 0.
- The list may contain elements of different data types unlike arrays in C or C++.
- Python has lots of in-built functionalities when it comes to list:
- cmp(list1, list2)
- len(list)
- max(list)
- min(list)
- list(sequence) – tuples are converted into a list
- Let’s see rest of the functions of list in python in action.
Note: This is Command Line Python
>>> a_list = [] >>> a_list [] >>> a_list = ["something",234] >>> a_list ['something', 234] >>> a_list[0] 'something' >>> a_list.count(234) 1 >>> a_list.append(334) >>> a_list ['something', 234, 334] >>> a_list.append(234) >>> a_list ['something', 234, 334, 234] >>> a_list.index(234) 1 >>> a_list.insert(1,"some string") >>> a_list ['something', 'some string', 234, 334, 234] >>> a_list.pop(234) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: pop index out of range >>> a_list.pop(1) 'some string' >>> a_list ['something', 234, 334, 234] >>> a_list.remove(234) >>> a_list ['something', 334, 234] >>> a_list.reverse() >>> a_list [234, 334, 'something'] >>> a_list.sort() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: '<' not supported between instances of 'str' and 'int' >>> another_list= [10,9,8,7] >>> another_list [10, 9, 8, 7] >>> another_list.sort() >>> another_list [7, 8, 9, 10] >>> sorted(another_list, reverse=True) [10, 9, 8, 7] >>> another_list [7, 8, 9, 10]
- By default, sort() does not require extra parameters. However, it has two (optional) parameters:
- reverse – if true then list is sorted in descending order
- key – a function that tells sort function the key for sort comparison
- sort() method doesn’t return. It makes changes to original list.
- If you want to keep original list intact then use sorted:
- sorted(a_list, key=…, reverse=…)