Creating lists in Python is very easy. One can use
 * 50to create a list of 50 elements filled with 0s. Another way that provides finer-grained control over the elements is iterating with a for loop and appending elements one by one. Yet, there is another way of creating a list through list comprehension. In case we would like to create a list of squares for numbers 1...100, we could do that with:
squares =  for n in range(1, 100): squares.append(n * n) print(squares)
squares = [n * n for n in range(1, 100)] print(squares)
Both of these programs would print the same output and create the same list of squares -
[1, 4, 9, 16, 25, 36, 49, 64, 81, ..., 9216, 9409, 9604, 9801].
So, the syntax for list comprehension is:
- The comprehension fits inside opening and closing brackets
forloop iterates over values
- The elements of the list come before the
forkeyword and can be dependent on the variable of the
In case of sending birthday invitations, imagine you have created a list of names that we would like to invite, but we have accidentally made them all lowercase. Now we can use a list comprehension to fix that:
invites = [ 'anna', 'alice', 'bob', 'simon', 'thomas' ] fixed =  for name in invites: fixed.append(name.title()) print(fixed)
invites = [ 'anna', 'alice', 'bob', 'simon', 'thomas' ] fixed = [name.title() for name in invites] print(fixed)
Both of these programs will print
['Anna', 'Alice', 'Bob', 'Simon', 'Thomas'].
nnames and surnames, you are asked to extract the names and print both the initial list and the list with only names.
The first line of the input contains a single integer
n. The next
The program should print the initial list first and then the list with only names.
3 Marshall Mathers Peter Hernandez Curtis Jackson
Marshall Mathers Peter Hernandez Curtis Jackson Marshall Peter Curtis
You can use
.split()to get the first element after splitting the string by whitespace.
You can even print with list comprehension:
l = ['hi', 'my', 'name', 'is'] [print(item) for item in l]
hi my name is