List Comprehensions

decal·2023년 1월 5일
0

study notes

목록 보기
7/12

A list comprehension is a way to create a new list like 'halved' by applying an expression on each element of an existing list, like 'prices'.

For example, you can shorten code from this:

prices = [10, 38, 40, 58, 62]
halved = []

for price in prices:
  half_price = price/2
  halved.append(half_price)

print(halved)

to this by using a list comprehension:

prices = [10, 38, 40, 58, 62]

halved = [price/2 for price in prices]
print(halved)

Both codes above give the same output:

[5.0, 19.0, 20.0, 29.0, 31.0]

So,

prices = [10, 38, 40, 58, 62]

halved_lc = [price/2 for price in prices]
print(halved_lc)

halved_loop = []
for price in prices:
  half_price = price/2
  halved_loop.append(half_price)

print(halved_loop)

Output:

[5.0, 19.0, 20.0, 29.0, 31.0]
[5.0, 19.0, 20.0, 29.0, 31.0]

Examples of expressions we can use when using list comprehension:

  • opposite
answers = [True, False, False]

opposite = []
for answer in answers:
  opposite.append(not answer)

print(opposite)

print([not answer for answer in answers])

output:

[False, True, True]
[False, True, True]
  • arithmetic (+, -, x, /)
expiry_years = [2018, 2020, 2019]

renewed = [year + 4 for year in expiry_years]

print(renewed)

output:

[2022, 2024, 2023]
  • copy the list
prices = [10, 38, 40, 58, 62]

prices_copy = [price for price in prices]

print(prices_copy)

output:

[10, 38, 40, 58, 62]

LC works with list elements of any type (numbers, booleans, tuples or strings)

For example:

names = ["Smith", "Miller", "Brown"]

prefixed = ["Mr. " + name for name in names]
print(prefixed)

Output:

['Mr. Smith', 'Mr. Miller', 'Mr. Brown']

Functions as Expressions

words = ["apple", "aligator", "abracadabra", "avatar"]

a_count = [word.count("a") for word in ]

print(a_count)

Output:

[1, 2, 5, 3]

We can make a function ('def') for an expression

prices = [10, 22, 30, 40, 58, 62]

def halve(num):
  return num/2

halved = [halve(price) for price in prices]

print(halved)

Output:

[5.0, 11.0, 15.0, 20.0, 29.0, 31.0]

Functions are useful when we want to apply more expressions.

For example, we can remove the tax before halving the prics like the following:

prices = [10, 22, 30, 40, 58, 60]

def halve(num):
  
  return 

halved = [halve(price) for price in prices]

print(halved)

Output:

[4.25, 9.35, 12.75, 17.0, 24.65, 25.5]

authors = ["Virginia Wolf", "John Steinbeck"]

def add_comma(name):
  parts = name.split(" ")
  return parts[1] + ", " + parts[0]

authors_update = [add_comma(name) for name in authors]

print(authors_update)

Output:

['Wolf, Virginia', 'Steinbeck, John']

words = ["apple", "aligator", "abracadabra", "avatar"]

def has_double_a(word):
  count = word.count("a")
  return count == 2

double_a = [has_double_a(word) for word in words]

print(double_a)

Output:

[False, True, False, False]

scores = [156, 70, 100]

def passed(score):
  with_bonus = score + 10
  passed = with_bonus > 90
  return passed

passing_scores = [passed(score) for score in scores]

print(passing_scores)

Output:

[True, False, True]

Filling with if statements

We can filter when creating a new list from an existing code using LC by using 'if' statement (conditional).

For example:

scores = [12, 47, 30, 29, 19, 35]
high_scores = [score for score in scores if score > 20]
print(high_scores)

Output:

[47, 30, 29, 35]

When using a conditional ('if'), the usual order is starting with the expression, followed by the for loop, and finishing with the if statement.

websites = ["nytimes.com", "lemonde.fr", "economist.com"]

french = [website for website in websites if website.count(".fr") == 1]

print(french)

Output

['lemonde.fr']

Negative Indexing and Deletion

Use negative indexing to retrieve values from the end of an indexable object, such as a list.

scores = [4.5, 5, 3, 4, 3.5, 4]
latest = scores[-1]
print(latest)

Output: 4

We can also modify list items in the given position like the following:

users = ["Jack", "Ahmed", "Elaine"]
users[-3] = "Jill"
print(users)

Output:

['Jill', 'Ahmed', 'Elaine']

We will encounter an error if we attempt to retrieve a value in a position outside the object's range.

Tuples are also ordered data structures and values can be retrieved, but they are immutable and so cannot be modified.


The del keyword allows us to delete objects, or items within a data structure.

winners = ["John", "Helen", "Sigmund", "Olaf"]
del winners[-1]
print(winners)

Output:

['John', 'Helen', 'Sigmund']

del can be used to delete any object, including data structures such as dictionaries, lists, and sets.

letters = {'a', 'b', 'c'}
del letters
print(letters)

Output:

NameError: name 'letters' is not defined

del can be used to delete unwanted key-value pairs from a dictionary.

product = {'category': 'book',
           'price': 4.99,
           'in_shop': True}

del 'in_shop'
print(product)

Output:

{'category': 'book', 'price': 4.99}

Slice Notation

We use slicing to retrieve multiple values from a list by assigning [start:stop] indices of the values from the variable.

ingredients = ["eggs", "flour", "sugar", "salt"]
print(ingredients[0:2])

Output:

['eggs', 'flour']

The start value can be positive, negative, or omitted completely. Negative values mean 'start this many elements back from the end'.

users = ["Alan", "Beth", "Carla", "Dennis"]

print(users[0:])
print(users[:])
print(users[-2:])

Output:

['Alan', 'Beth', 'Carla', 'Dennis'] 
['Alan', 'Beth', 'Carla', 'Dennis'] 
['Carla', 'Dennis']

Specifying a range outside the length of a list will return an empty list, rather than resulting in an error.

Output: []

A value after the colon : represents where the slice should stop . Note that the element in the stop position is not included.

scores = [50, 40, 30, 20, 10]
print(scores[:2])
print(scores[2:4])

Output:

[50, 40] 
[30, 20]

If we use a start value of 0 (or do not include one), a positive stop value will be equal to the number of elements returned.

grades = ['A', 'B', 'C', 'D', 'E']
print(grades[])

Output:

['A', 'B', 'C']

A start index later in the list than the stop index in the [start:stop] format won't result in an error, but will return an empty list.

We can also use a format with two colons, [start:stop:step] , where step determines how Python steps between start and end.

alphabet = ["A", "B", "C", "D", "E", "F"]

print(alphabet[1:6:2])

Output:

['B', 'D', 'F']

We can use the step value with no start or end value. By default this will work from the start to the end of the full original list.

Each value can be positive, negative, or omitted completely. To use the step value, we must always have two preceeding colons.

flowers = ["azaelea", "buttercup", "carnation", "daffodil"]

print(flowers[2::-1])
print(flowers[:3:2])

Output:

['carnation', 'buttercup', 'azaelea'] ['azaelea', 'carnation']

step can be negative, which allows us to use a start value larger than the end value. The order of the elements is reversed.

friends = ["Anna", "Bella", "Carrie", "Diana", "Eleanor"]

print(friends[3:0:-1])

Output:

['Diana', 'Carrie', 'Bella']

If no start or end value are given, Python will automatically work from the end of a list if a negative step is provided.

countries = ['Andorra', "Brazil", "China", "Denmark", "Egypt"]

print(countries[::])

Output:

['Egypt', 'Brazil']

An empty list, rather than an error, will be returned if there are no matching indexes. The step always works from the start value.

scores = [100, 200, 300, 400, 500]
print(scores[0:2:-1])
print(scores[41-1])

Output:

[] [500, 400, 300]

Complete the start:stop:step notation so that [5, 5, 5] is printed.

ratings = [3, 4, 2, 5, 1, 5, 4, 5]
print(ratings[-1:2:-2])

0개의 댓글