= ['a', 'b', 'c']
keys = [1, 2, 3]
values
# Create the dictionary using the dict constructor and zip
= dict(zip(keys, values))
result_dict result_dict
{'a': 1, 'b': 2, 'c': 3}
How can I create dict from two list with keys from the first list and values from the secound?
Traditional
= {}
mapping for key, value in zip(key_list, value_list):
= value mapping[key]
Better way:
dict
Constructor= ['a', 'b', 'c']
keys = [1, 2, 3]
values
# Create the dictionary using the dict constructor and zip
= dict(zip(keys, values))
result_dict result_dict
{'a': 1, 'b': 2, 'c': 3}
= ['a', 'b', 'c']
keys = [1, 2, 3]
values
# Create the dictionary using a dictionary comprehension
= {key: value for key, value in zip(keys, values)}
result_dict result_dict
{'a': 1, 'b': 2, 'c': 3}
from itertools import zip_longest
= ['a', 'b', 'c']
keys = [1, 2]
values
# Create the dictionary using zip_longest to handle unequal lengths
= {key: value for key, value in zip_longest(keys, values)}
result_dict result_dict
{'a': 1, 'b': 2, 'c': None}
= [1, 2, 3]
a = list(a)
c
== c
a is c a
False
Since the list function always creates a new Python list (i.e., a copy)
= [1, 2, 3]
list1 = [4, 5, 6] list2
+
Operator= list1 + list2
combined_list combined_list
[1, 2, 3, 4, 5, 6]
extend()
Method
list1.extend(list2) list1
[1, 2, 3, 4, 5, 6]
*
Operator (Python 3.5+)= [*list1, *list2, 7]
combined_list combined_list
[1, 2, 3, 4, 5, 6, 4, 5, 6, 7]
= [item for sublist in (list1, list2) for item in sublist]
combined_list combined_list
[1, 2, 3, 4, 5, 6, 4, 5, 6]
itertools.chain()
Functionimport itertools
= list(itertools.chain(list1, list2))
combined_list combined_list
[1, 2, 3, 4, 5, 6, 4, 5, 6]
Input: [["a"], ["b", "c"], ["d"]]
Desired output: ["a", "b", "c", "d"]
=[["a"], ["b", "c"], ["d"]]
nested_list = [item for sublist in nested_list for item in sublist]
flattened_list flattened_list
['a', 'b', 'c', 'd']
itertools.chain
This is particularly useful for larger datasets:
import itertools
= [["a"], ["b", "c"], ["d"]]
nested_list = list(itertools.chain(*nested_list))
flattened_list flattened_list
['a', 'b', 'c', 'd']
sum()
with an Empty Listmay not be as efficient for very large lists:
= [["a"], ["b", "c"], ["d"]]
nested_list = sum(nested_list, [])
flattened_list flattened_list
['a', 'b', 'c', 'd']
= {'a', 'b', 'c' }
a = {'c', 'd'}
b
print(a | b)
print(a & b)
print(a - b)
print(a ^ b) # Symmetric difference
{'c', 'a', 'd', 'b'}
{'c'}
{'b', 'a'}
{'a', 'd', 'b'}
= [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a
2:5] # [2, 3, 4]
a[3] # [0, 1, 2]
a[:-3:] # [7, 8, 9]
a[2] # [0, 2, 4, 6, 8 ]
a[::-2] # [9, 7, 5, 3, 1 ]
a[::0:5:2] # [0, 2]
a[5:0:-2] # [5, 3, 1]
a[5:1] # [0, 1, 2, 3, 4]
a[:5:-1] # [9, 8, 7, 6]
a[:5::1] # [5, 6, 7, 8, 9]
a[5::-1] # [5, 4, 3, 2, 1, 0]
a[5:0:-1] # [5, 4, 3, 2, 1] a[
[5, 4, 3, 2, 1]
= slice(0, 5)
firstfive = 'hello world'
s
firstfive
slice(0, 5, None)
print(s[firstfive])
hello