You are on page 1of 17

Indexing and Slicing

List Comprehensions
Indexing and Slicing
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[-1]

'lobster'

>>> a[-2]

'ham'

>>> a[-5]

'egg'

>>> a[-6]

'spam'

>>> a[-len(a)]

'spam'

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[2:5]

['bacon', 'tomato', 'ham']

>>> a[-5:-2]

['egg', 'bacon', 'tomato']

>>> a[1:4]

['egg', 'bacon', 'tomato']

>>> a[-5:-2] == a[1:4]

True

Omitting the first and/or last index:

 Omitting the first index a[:n] starts the slice at the beginning of the
list.
 Omitting the last index a[m:] extends the slice from the first index m to
the end of the list.
 Omitting both indexes a[:] returns a copy of the entire list, but unlike
with a string, it’s a copy, not a reference to the same object.
>>> a

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[:4]

['spam', 'egg', 'bacon', 'tomato']

>>> a[0:4]

['spam', 'egg', 'bacon', 'tomato']

>>> a[2:]

['bacon', 'tomato', 'ham', 'lobster']

>>> a[2:len(a)]

['bacon', 'tomato', 'ham', 'lobster']

>>> a

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[:]

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a == a[:]

True

>>> a is a[:]

False

>>> s = 'mybacon'

>>> s[:]

'mybacon'

>>> s == s[:]

True

>>> s is s[:]

True
A stride can be added to your slice notation. Using an additional : and a
third index designates a stride (also called a step) in your slice notation. The
stride can be either postive or negative:
>>> a

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[0:6:2]

['spam', 'bacon', 'ham']

>>> a[1:6:2]

['egg', 'tomato', 'lobster']

>>> a[6:0:-2]

['lobster', 'tomato', 'egg']

>>> a

['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[::-1]

['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']

List Comprehensions?

List comprehensions provide us with a simple way to create a


list based on some iterable. During the creation, elements from the
iterable can be conditionally included in the new list
and transformed as needed.

An iterable is something you can loop over.

The components of a list comprehension are:

 Output Expression (Optional)

 Iterable
 Iterator variable which represents the members of the iterable

numbers=[1,2,3,4,5]

squares = [number**2 for number in numbers]

print(squares)

We can also create more advanced list comprehensions which


include a conditional statement on the iterable.

numbers = [1, 2, 3, 4, 5]

squares = [number**2 for number in numbers if number > 2]

print(squares)

List Comprehensions vs loops

The list comprehensions are more efficient both computationally and


in terms of coding space and time than a for loop

numbers = [1, 2, 3, 4, 5]

squares = []

for number in numbers:

if number > 2:

squares.append(number**2)

print(squares)
What about the computational speed? We can use the timeit library
to compare the speed of a for loop vs the speed of a list
comprehension. We can also pass the number of executions using
the number argument. We’ll set this argument to 1 million.

import timeit

def squares(size):

result = []

for number in range(size):

result.append(number*number)

return result

def squares_comprehension(size):

return [number*number for number in range(size)]

print(timeit.timeit("squares(50)", "from __main__ import squares", number = 1_000_000))

print(timeit.timeit("squares_comprehension(50)", "from __main__ import


squares_comprehension", number = 1_000_000))

List Comprehensions vs map and filter

Lambda Functions

Lambda functions are small anonymous functions. They can have


any number of arguments but can have only one expression.
Mostly, the lambda functions are passed as parameters to functions
which expect a function object as one of their parameters
like map and filter.

Map Function

The map function returns an iterator that applies a function to


every item of iterable, yielding the results. Let’s compare it with a
list comprehension.

# Map

numbers = [1, 2, 3, 4, 5]

squares = list(map(lambda x: x**2, numbers))

print(squares)

# List Comprehension

numbers = [1, 2, 3, 4, 5]

squares = [number**2 for number in numbers]

print(squares)

Filter Function

The filter function constructs an iterator from elements


of iterable for which the passed function returns true. Again, let’s
compare the filter function versus the list comprehensions.

# Filter
numbers = [1, 2, 3, 4, 5]

filtered = list(filter(lambda x: x % 2 == 0, numbers))

print(filtered)

# List Comprehension

numbers = [1, 2, 3, 4, 5]

filtered = [number for number in numbers if number % 2 == 0]

print(filtered)

More Complex List Comprehensions

Additionally, when we’re creating a list comprehension we can


have many conditional statements on the iterable.

numbers = [1, 2, 3, 4, 5, 6, 18, 20]

squares = [number for number in numbers if number % 2 == 0 if number % 3 == 0]

print(squares)

Moreover, we can also have an if-else clause on the output


expression.

numbers = [1, 2, 3, 4, 5, 6, 18, 20]

squares = ["small" if number < 10 else "big" for number in numbers if number % 2 == 0 if
number % 3 == 0]

print(squares)
Readability

We can see that some list comprehensions can be very complex and
it’s hard to read them. Python allows line breaks between brackets
and braces. We can use this to make our complex comprehension
more readable.For example, we can our last transform example to
this:

numbers = [1, 2, 3, 4, 5, 6, 18, 20]

squares = [

"small" if number < 10 else "big"

for number in numbers

if number % 2 == 0

if number % 3 == 0]

print(squares)

Nested For Loops

In some cases, we need nested for loops to complete some task. In this
cases, we can also use a list comprehension to achieve the same
result.

Imagine that we have a matrix and we want to flatten it. We can do


this easily with two for loops like this:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flattened = []

for row in matrix:

for item in row:


flattened.append(item)

print(flattened)

We can achieve the same result using a list comprehension.


The order of the for clauses remain the same as in the original for
loops.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

flattened = [item for row in matrix for item in row]

print(flattened)

Nested List Comprehensions

In other cases, we may need to create a matrix. We can do that


with nested list comprehensions

matrix = [[item for item in range(5)] for row in range(3)]

print(matrix)

Other Comprehensions

In Python, we have also dictionary comprehensions and set comprehensions

Dictionary Comprehensions

To create a dictionary comprehension we just need to change the


brackets [] to curly braces {}. Additionally, in the output expression,
we need to separate key and value by a colon :.
prices = {"beer": 2, "fish": 5, "apple": 1}

float_prices = {key:float(value) for key, value in prices.items()}

print(float_prices)

Set Comprehensions

To create a set comprehension we only need to change the


brackets [] to curly braces {}.

numbers = [10, 10, 20, 30, 12, -20, 0, 1]

unique_squares = {number**2 for number in numbers}

print(unique_squares)
Differences between
List, Tuple, Set and
Dictionary in Python

List

Lists are one of the most commonly used data structures provided by
python; they are a collection of iterable, mutable and ordered data.
They can contain duplicate data.

Tuple

Tuples are similar to lists. This collection also has iterable, ordered,
and (can contain) repetitive data, just like lists. But unlike lists,
tuples are immutable.

Set

Set is another data structure that holds a collection of unordered,


iterable and mutable data. But it only contains unique elements.

Dictionary

Unlike all other collection types, dictionaries strictly contain key-


value pairs.

 In Python versions < 3.7: is an unordered collection of data.


 In Python v3.1: a new type of dictionary called ‘OrderedDict’
was introduced, which was similar to dictionary in python; the
difference was that orderedDict was ordered (as the name
suggests)
 In the latest version of Python, i.e. 3.7: Finally, in python 3.7,
dictionary is now an ordered collection of key-value pairs. The
order is now guaranteed in the insertion order, i.e. the order in
which they were inserted.

Collection VS Features Mutable Ordered Indexing Duplicate Data


List ✔ ✔ ✔ ✔
Tuple � ✔ ✔ ✔
Set ✔ � � �
Dictionary ✔ ✔ ✔ �

list1 = [1 , 2, 'abc', 3, 'def']

list2 = []

list3 = list((1,2,3))

print(list1)

# Output: [1, 2, 'abc', 3, 'def']

print(list2)

# Output: [ ]

print(list3)

# Output: [1, 2, 3]

______________________________________________________________________

tuple1=(1,2,'abc', 3, 4)

tuple2=()

tuple3=tuple((1,3,5,"hello"))
print(tuple1)

# Output: (1, 2, 'abc', 3, 4)

print(tuple2)

# Output: () )

print(tuple3)

# Output: (1, 2, 3, 'hello')

____________________________________________________________

set1={1,2,3,'abc', 6}

print(set1)

# Output: set([1, 2, 3, 'abc', 6])

____________________________________________________________

dict1={"key1":"value1","key2":"value2"}

dict2={}

dict3=dict({1:"one",2:"two",3:"three"})

print(dict1)

# Output: {'key2': 'value2', 'key1': 'value1'}

print(dict2)

# Output: {}

print(dict3)

# Output: {1: 'one', 2: 'two', 3: 'three'}

________________________________________________________________

list1 = [1, 2, "hello", 3]

print(list1[2])

_____________________________________________________________________

tuple1 = (1, 2, "hello", 3)

print(tuple1[2])

set1={1,2,3,4,5}

print(set1)
dict1={"one":1, "two": 2, "three": 3}

print(dict1.keys())

# all the keys are printed

# Output: ['three', 'two', 'one']

print(dict1.values())

# Output: [3, 2, 1]

# all the values are printed

print(dict1['two'])

# output: 2

________________________________________________________________________________

list1=["one","two","three"]

list1.append("four") print(list1)

# output: ['one', 'two', 'three', 'four']

___________________________________________________________________

set1 = { "one", "two", "three"}

set1.add("four") print(set1)

# output: ['four', 'two', 'one', 'three'] i.e. in any random order

____________________________________________________________________________

dict1={"India":"IN","Russia":"RU","Australia":"AU"} dict1.update({"Canada":"CA"})

print(dict1)

# Output: {'Canada': 'CA', 'Australia': 'AU', 'India': 'IN', 'Russia': 'RU'}

dict1.pop("Australia") print(dict1)

# Output: {'Canada': 'CA', 'India': 'IN', 'Russia': 'RU'}

________________________________________________________________________________

list1=["one","two","three", “four”]

list1.pop() print(list1)

# output: ['one', 'two', 'three']

list1.pop()

print(list1)
# output: ['one', 'two']

_____________________________________________________________

set1 = {"one","two","three"}

set1.pop()

print(set1)

# output: ['one', 'two'] (in any random order)

_____________________________________________________________________

dict1={"India":"IN","Russia":"RU","Australia":"AU"}

dict1.pop('Russia') print(dict1)

# Output: {'Australia': 'AU', 'India': 'IN'}

___________________________________________________________________________

list1 = [100, 3, 4, 12,1]

list1.sort()

print(list1)

# output: [1, 3, 4, 12, 100]

list2 = ['car', 'scooter', 'plane']

print(list2)

# output: ['car', 'scooter', 'plane']

________________________________________________________________________________

dict1={"India":"IN","Russia":"RU","Australia":"AU"}

print(sorted(dict1))

# output: ['Australia', 'India', 'Russia']|

_________________________________________________________________________________

list1 = [100, 3, 4, 12,1]

# index() returns index for 4 in list1

print(list1.index(4))

# output: 2

tuple1 = (100, 3, 4, 12,1)

# index() returns index for 4 in tuple1


print(tuple1.index(4))

# output: 2

___________________________________________________________________

dict1={"India":"IN","Russia":"RU","Australia":"AU"} print(dict1['Australia'])

# Output: AU

___________________________________________________________________________

list1 = [100, 3, 4, 12,1]

list1.reverse() print(list1)

# Output: [1, 12, 4, 3, 100]

________________________________________________________________

list1 = [1,2,3,6,2,2,2]

print(list1.count(2))

tuple1 = (1,2,3,6,2,2,2)

print(tuple1.count(2))

You might also like