Python list:
- Elements in a list do not require to be of the same type.
- It can be a mixture of elements like numbers, strings, other lists and so on.
- Allows duplicate members.
- Lists can have sublists as elements. These sublists may contain more sublists as well
a = [1, 2.2, ‘python’, [a,b,c]]
- Lists can be updated while program is running, whereas in C programming language, the size of an array has to be fixed at compile time.
- To declare a list, Items separated by commas are enclosed within brackets [ ].
- List is an ordered sequence of items.
- The elements can be accessed via indices using slicing operator i.e. []
- Index starts form 0 in Python. The index must be an integer. We can’t use float or other types, this will result into TypeError.
- Python allows negative indexing for its sequences.
- The index of -1 refers to the last item, -2 to the second last item and so on.
- Lists are mutable, meaning, value of elements of a list can be altered.
- We can use assignment operator (=) to change an item or a range of items.
- We can add one item to a list using append() method or add several items using extend() method.
- We can also use + operator to combine two lists. This is also called concatenation.
a = [1, 3, 5]
print(a + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
- We can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.
a = [1, 9]
a.insert(1,3)
Python List Methods:
- Methods that are available with list object in Python programming are listed below.
- They are accessed as list.method().
List Comprehension:
- List comprehension is an elegant and concise way to create a new list from an existing list in Python.
- List comprehension consists of an expression followed by for statement inside square brackets.
- Here is an example to make a list with each item being increasing power of 2.
- Above code is equivalent to
power_2 = []
for x in range(10):
power_2.append(2 ** x)
- A list comprehension can optionally contain more for/if statements as nested loops.
Other List Operations in Python:
- List Membership Test:
- We can test if an item exists in a list or not, using the keyword in.
- Iterating Through a List:
- Using a for loop we can iterate though each item in a list.
for fruit in [‘apple’,’banana’,’mango’]:
print(“I like”,fruit)
Built-in functions with List:
- reduce()
Apply a particular function passed in argument to all elements in list, stores the intermediate result and only returns the final summation value
- sum()
Sums up the numbers in the list
- ord()
Returns an integer representing the Unicode code point of the given Unicode character
- cmp()
Compares lists. If first list is “greater” than second list, returns 1
- max()
return maximum element in given list
- min()
return minimum element in given list
- all()
- any()
- len()
- enumerate()
- accumulate()
- filter()
- map()
- lambda()