List Comprehension: Elegant way to create new
List
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.
1. pow2 = [2 ** x for x in range(10)]
2.
3. # Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
4. print(pow2)
This code is equivalent to
1. pow2 = []
2. for x in range(10):
3. [Link](2 ** x)
A list comprehension can optionally contain more for or if statements. An
optional if statement can filter out items for the new list. Here are some examples.
1. >>> pow2 = [2 ** x for x in range(10) if x > 5]
2. >>> pow2
3. [64, 128, 256, 512]
4. >>> odd = [x for x in range(20) if x % 2 == 1]
5. >>> odd
6. [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
7. >>> [x+y for x in ['Python ','C '] for y in
['Language','Programming']]
8. ['Python Language', 'Python Programming', 'C Language', 'C
Programming']
Other List Operations in Python
List Membership Test
We can test if an item exists in a list or not, using the keyword in.
1. my_list = ['p','r','o','b','l','e','m']
2.
3. # Output: True
4. print('p' in my_list)
5.
6. # Output: False
7. print('a' in my_list)
8.
9. # Output: True
10. print('c' not in my_list)
Iterating Through a List
Using a for loop we can iterate though each item in a list.
1. for fruit in ['apple','banana','mango']:
2. print("I like",fruit)
Python List Programs
Sum all the items in a list
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
Multiplies all the items in a list
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
Get the largest number from a list
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
Get the smallest number from a list
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
Count the number of strings where the
string length is 2 or more and the first and
last character are same from a given list of
strings
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
print(match_words(['abc', 'xyz', 'aba', '1221']))
Get a list, sorted in increasing order by the
last element in each tuple from a given list
of non-empty tuples
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
def last(n): return n[-1]
def sort_list_last(tuples):
return sorted(tuples, key=last)
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2,
1)]))
Sample Output:
[(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
Remove duplicates from a list
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Copy
Sample Output:
{40, 10, 80, 50, 20, 60, 30}
Check a list is empty or not
l = []
if not l:
print("List is empty")
Copy
Sample Output:
List is empty
Clone or copy a list
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)
Takes two lists and returns True if they
have at least one common member
def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))
Shuffle and print a specified list
from random import shuffle
color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
shuffle(color)
print(color)
Generate all permutations of a list in
Python
import itertools
print(list([Link]([1,2,3])))
Difference between the two lists
list1 = [1, 2, 3, 4]
list2 = [1, 2]
print(list(set(list1) - set(list2)))
Access the index of a list
nums = [5, 15, 35, 8, 98]
for num_index, num_val in enumerate(nums):
print(num_index, num_val)
Convert a list of characters into a string
s = ['a', 'b', 'c', 'd']
str1 = ''.join(s)
print(str1)
Find the index of an item in a specified list
num =[10, 30, 4, -6]
print([Link](30))
Append a list to the second list
list1 = [1, 2, 3, 0]
list2 = ['Red', 'Green', 'Black']
final_list = list1 + list2
print(final_list)
Select an item randomly from a list
import random
color_list = ['Red', 'Blue', 'Green', 'White', 'Black']
print([Link](color_list))
Check whether two lists are circularly
identical
list1 = [10, 10, 0, 0, 10]
list2 = [10, 10, 10, 0, 0]
list3 = [1, 10, 10, 0, 0]
print('Compare list1 and list2')
print(' '.join(map(str, list2)) in ' '.join(map(str, list1 *
2)))
print('Compare list1 and list3')
print(' '.join(map(str, list3)) in ' '.join(map(str, list1 *
2)))
Get unique values from a list
my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
Original List : [10, 20, 30, 40, 20, 50, 60, 40]
List of unique numbers : [40, 10, 50, 20, 60, 30]
Get the frequency of the elements in a list
import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print("Original List : ",my_list)
ctr = [Link](my_list)
print("Frequency of the elements in the List : ",ctr)
Copy
Sample Output:
Original List : [10, 10, 10, 10, 20, 20, 20, 20, 40, 40, 50,
50, 30]
Frequency of the elements in the List : Counter({10: 4, 20:
4, 40: 2, 50: 2, 30: 1})
Find the second largest number in a list
def second_largest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] == numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[-2]
print(second_largest([1,2,3,4,4]))
print(second_largest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_largest([2,2]))
print(second_largest([1]))
Count the number of elements in a list
within a specified range
def count_range_in_list(li, min, max):
ctr = 0
for x in li:
if min <= x <= max:
ctr += 1
return ctr
list1 = [10,20,30,40,40,40,70,80,99]
print(count_range_in_list(list1, 40, 100))
list2 = ['a','b','c','d','e','f']
print(count_range_in_list(list2, 'a', 'e'))
Check whether a list contains a sublist
def is_Sublist(l, s):
sub_set = False
if s == []:
sub_set = True
elif s == l:
sub_set = True
elif len(s) > len(l):
sub_set = False
else:
for i in range(len(l)):
if l[i] == s[0]:
n = 1
while (n < len(s)) and (l[i+n] == s[n]):
n += 1
if n == len(s):
sub_set = True
return sub_set
a = [2,4,3,5,7]
b = [4,3]
c = [3,7]
print(is_Sublist(a, b))
print(is_Sublist(a, c))
Copy
Sample Output:
True
False
Create a list by concatenating a given list
which range goes from 1 to n
Sample list : ['p', 'q']
n =5
Sample Output : ['p1', 'q1', 'p2', 'q2', 'p3', 'q3', 'p4', 'q4', 'p5', 'q5']
my_list = ['p', 'q']
n = 4
new_list = ['{}{}'.format(x, y) for y in range(1, n+1) for x in my_list]
print(new_list)
Find common items from two lists
color1 = "Red", "Green", "Orange", "White"
color2 = "Black", "Green", "White", "Pink"
print(set(color1) & set(color2))
Create multiple lists
obj = {}
for i in range(1, 21):
obj[str(i)] = []
print(obj)
Sample Output:
{'1': [], '8': [], '14': [], '5': [], '17': [], '9': [], '2':
[], '7': [], '16': [], '19': [], '4': [], '18':
[], '13': [], '3': [], '15': [], '11': [], '20': [], '6': [],
'12': [], '10': []}
Split a list into different variables
color = [("Black", "#000000", "rgb(0, 0, 0)"), ("Red",
"#FF0000", "rgb(255, 0, 0)"),
("Yellow", "#FFFF00", "rgb(255, 255, 0)")]
var1, var2, var3 = color
print(var1)
print(var2)
print(var3)
Generate groups of five consecutive
numbers in a list
l = [[5*i + j for j in range(1,6)] for i in range(5)]
print(l)
Copy
Sample Output:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16,
17, 18, 19, 20], [21, 22, 23, 24, 25]]
Convert a pair of values into a sorted
unique array
L = [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1, 2), (3, 4), (3, 4),
(7, 8), (9, 10)]
print("Original List: ", L)
print("Sorted Unique Data:",sorted(set().union(*L)))
Copy
Sample Output:
Original List: [(1, 2), (3, 4), (1, 2), (5, 6), (7, 8), (1,
2), (3, 4), (3, 4), (7, 8), (9, 10)]
Sorted Unique Data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Insert an element before each element of a
list
color = ['Red', 'Green', 'Black']
print("Original List: ",color)
color = [v for elt in color for v in ('c', elt)]
print("Original List: ",color)
Copy
Sample Output:
Original List: ['Red', 'Green', 'Black']
Original List: ['c', 'Red', 'c', 'Green', 'c', 'Black']
Concatenate elements of a list
color = ['red', 'green', 'orange']
print('-'.join(color))
print(''.join(color))
Copy
Sample Output:
red-green-orange
redgreenorange
Convert a string to a list
import ast
color ="['Red', 'Green', 'White']"
print(ast.literal_eval(color))
Copy
Sample Output:
['Red', 'Green', 'White']
Check if all items of a list is equal to a
given string
color1 = ["green", "orange", "black", "white"]
color2 = ["green", "green", "green", "green"]
print(all(c == 'blue' for c in color1))
print(all(c == 'green' for c in color2))
Copy
Sample Output:
False
True
Extend a list without append
x = [10, 20, 30]
y = [40, 50, 60]
x[:0] =y
print(x)
Copy
Sample Output:
[40, 50, 60, 10, 20, 30]
Remove duplicates from a list of lists
Sample list : [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
New List : [[10, 20], [30, 56, 25], [33], [40]]
import itertools
num = [[10, 20], [40], [30, 56, 25], [10, 20], [33], [40]]
print("Original List", num)
[Link]()
new_num = list(num for num,_ in [Link](num))
print("New List", new_num)
Copy
Sample Output:
Original List [[10, 20], [40], [30, 56, 25], [10, 20], [33],
[40]]
New List [[10, 20], [30, 56, 25], [33], [40]]
List: Cheat Sheet
Making a list:
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
Accessing elements:
# Getting the first element
first_col = colors[0]
# Getting the second element
second_col = colors[1]
# Getting the last element
newest_col = colors[-1]
Modifying individual items:
# Changing an element
colors[0] = 'Yellow'
colors[-2] = 'Red'
Adding elements:
# Adding an element to the end of the list
[Link]('Orange')
# Starting with an empty list
colors = []
[Link]('Red')
[Link]('Blue')
[Link]('Green')
# Inserting elements at a particular position
[Link](0, 'Violet')
[Link](2, 'Purple')
Removing elements:
# Deleting an element by its position
del colors[-1]
# Removing an item by its value
[Link]('Green')
Popping elements:
# Pop the last item from a list
most_recent_col = [Link]()
print(most_recent_col)
# Pop the first item in a list
first_col = [Link](0)
print(first_col)
List length:
# Find the length of a list
num_colors = len(colors)
print("We have " + str(num_colors) + " colors.")
Sorting a list:
# Sorting a list permanently
[Link]()
# Sorting a list permanently in reverse alphabetical order
[Link](reverse=True)
# Sorting a list temporarily
print(sorted(colors))
print(sorted(colors, reverse=True))
# Reversing the order of a list
[Link]()
Looping through a list:
# Printing all items in a list
for col in colors:
print(col)
# Printing a message for each item, and a separate message
afterwards
for col in colors:
print("Welcome, " + col + "!")
print("Welcome, we're glad to see you all!")
The range() function:
# Printing the numbers 0 to 2000
for num in range(2001):
print(num)
# Printing the numbers 1 to 2000
for num in range(1, 2001):
print(num)
# Making a list of numbers from 1 to a million
nums = list(range(1, 1000001))
Simple statistics:
# Finding the minimum value in a list
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_min = min(nums)
# Finding the maximum value
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
num_max = max(nums)
# Finding the sum of all numbers
nums = [23, 22, 44, 17, 77, 55, 1, 65, 82, 2]
total_num = sum(nums)
Slicing a list:
# Getting the first three items
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
first_three = colors [:3]
# Getting the middle three items
middle_three = colors[1:4]
# Getting the last three items
last_three = colors[-3:]
Copying a list:
# Making a copy of a list
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
copy_of_colors = colors[:]
List of Comprehensions:
# Using a loop to generate a list of square numbers
squr = []
for x in range(1, 11):
sq = x**2
[Link](sq)
# Using a comprehension to generate a list of square numbers
squr = [x**2 for x in range(1, 11)]
# Using a loop to convert a list of names to upper case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = []
for cols in colors:
upper_cols.append([Link]())
# Using a comprehension to convert a list of names to upper
case
colors = ['Red', 'Blue', 'Green', 'Black', 'White']
upper_cols = [[Link]() for cols in colors]