Accessing list values-
Python lists are zero-indexed, and act like arrays in other languages.
lst = [1, 2, 3, 4]
lst[0] # 1
lst[1] # 2
Attempting to access an index outside the bounds of the list will raise an IndexError.
lst[4] # IndexError: list index out of range
Negative indices are interpreted as counting from the end of the list.
lst[-1] # 4
lst[-2] # 3
lst[-5] # IndexError: list index out of range
This is functionally equivalent to
lst[len(lst)-1] # 4
Lists allow to use slice notation as lst[start:end:step]. The output of the slice notation is a new list containing elements from index start to end-1. If options are omitted start defaults to beginning of list, end to end of list and step to 1:
lst[1:] # [2, 3, 4]
lst[:3] # [1, 2, 3]
lst[::2] # [1, 3]
lst[::-1] # [4, 3, 2, 1]
lst[-1:0:-1] # [4, 3, 2]
lst[5:8] # [] since starting index is greater than length of lst, returns empty list
lst[1:10] # [2, 3, 4] same as omitting ending index
With this in mind, you can print a reversed version of the list by calling
lst[::-1] # [4, 3, 2, 1]
When using step lengths of negative amounts, the starting index has to be greater than the ending index otherwise the result will be an empty list.
lst[3:1:-1] # [4, 3]
Using negative step indices are equivalent to the following code:
reversed(lst)[0:2] # 0 = 1 -1
# 2 = 3 -1
The indices used are 1 less than those used in negative indexing and are reversed.
Advanced slicing
When lists are sliced the __getitem__() method of the list object is called, with a slice object. Python has a builtin slice method to generate slice objects. We can use this to store a slice and reuse it later like so,
data = 'chandan purohit 22 2000' #assuming data fields of fixed length
name_slice = slice(0,19)
age_slice = slice(19,21)
salary_slice = slice(22,None)
#now we can have more readable slices
print(data[name_slice]) #chandan purohit
print(data[age_slice]) #'22'
print(data[salary_slice]) #'2000'
This can be of great use by providing slicing functionality to our objects by overriding __getitem__ in our class.
Checking if list is empty
The emptiness of a list is associated to the boolean False, so you don't have to check len(lst) == 0, but just lst or not lst
lst = []
if not lst:
print("list is empty")
# Output: list is empty
Iterating over a list
Python supports using a for loop directly on a list:
my_list = ['foo', 'bar', 'baz']
for item in my_list:
print(item)
# Output: foo
# Output: bar
# Output: baz
You can also get the position of each item at the same time:
for (index, item) in enumerate(my_list):
print('The item in position {} is: {}'.format(index, item))
# Output: The item in position 0 is: foo
# Output: The item in position 1 is: bar
# Output: The item in position 2 is: baz
The other way of iterating a list based on the index value:
for i in range(0,len(my_list)):
print(my_list[i])
#output:
>>>
foo
bar
Note that changing items in a list while iterating on it may have unexpected results:
for item in my_list:
if item == 'foo':
del my_list[0]
print(item)
# Output: foo
# Output: baz
In this last example, we deleted the first item at the first iteration, but that caused bar to be skipped
Q.1 Checking whether an item is in a list
Python makes it very simple to check whether an item is in a list. Simply use the in operator.
lst = ['test', 'twest', 'tweast', 'treast']
'test' in lst
# Out: True
'toast' in lst
# Out: False
Note: the in operator on sets is asymptotically faster than on lists. If you need to use it many times on potentially large lists, you may want to convert your list to a set, and test the presence of elements on the set.
slst = set(lst)
'test' in slst
# Out: True
Any and All
You can use all() to determine if all the values in an iterable evaluate to True
nums = [1, 1, 0, 1]
all(nums)
# False
chars = ['a', 'b', 'c', 'd']
all(chars)
# True
Likewise, any() determines if one or more values in an iterable evaluate to True
nums = [1, 1, 0, 1]
any(nums)
# True
vals = [None, None, None, False]
any(vals)
# False
While this example uses a list, it is important to note these built-ins work with any iterable, including generators.
vals = [1, 2, 3, 4]
any(val > 12 for val in vals)
# False
any((val * 2) > 6 for val in vals)
# True
Reversing list elements
You can use the reversed function which returns an iterator to the reversed list:
In [3]: rev = reversed(numbers)
In [4]: rev
Out[4]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Note that the list "numbers" remains unchanged by this operation, and remains in the same order it was originally.
To reverse in place, you can also use the reverse method.
You can also reverse a list (actually obtaining a copy, the original list is unaffected) by using the slicing syntax, setting the third argument (the step) as -1:
In [1]: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [2]: numbers[::-1]
Out[2]: [9, 8, 7, 6, 5, 4, 3, 2, 1]
Concatenate and Merge lists-
1. The simplest way to concatenate list1 and list2:
merged = list1 + list2
2. zip returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables:
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
for a, b in zip(alist, blist):
print(a, b)
# Output:
# a1 b1
# a2 b2
# a3 b3
If the lists have different lengths then the result will include only as many elements as the shortest one:
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3', 'b4']
for a, b in zip(alist, blist):
print(a, b)
# Output:
# a1 b1
# a2 b2
# a3 b3
alist = []
len(list(zip(alist, blist)))
# Output:
# 0
For padding lists of unequal length to the longest one with Nones use itertools.zip_longest
(itertools.izip_longest in Python 2)
alist = ['a1', 'a2', 'a3']
blist = ['b1']
clist = ['c1', 'c2', 'c3', 'c4']
for a,b,c in itertools.zip_longest(alist, blist, clist):
print(a, b, c)
# Output:
# a1 b1 c1
# a2 None c2
# a3 None c3
# None None c4
3. Insert to a specific index values:
alist = [123, 'xyz', 'zara', 'abc']
alist.insert(3, [2009])
print("Final List :", alist)
Output:
Final List : [123, 'xyz', 'zara', 2009, 'abc']
Length of a list-
Use len() to get the one-dimensional length of a list.
len(['one', 'two']) # returns 2
len(['one', [2, 3], 'four']) # returns 3, not 4
len() also works on strings, dictionaries, and other data structures similar to lists.
Note that len() is a built-in function, not a method of a list object.
Also note that the cost of len() is O(1), meaning it will take the same amount of time to get the length of a list regardless of its length.