keys = ['a', 'b', 'c']
values = [1, 2, 3]
# Create the dictionary using the dict constructor and zip
result_dict = dict(zip(keys, values))
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):
mapping[key] = valueBetter way:
dict Constructorkeys = ['a', 'b', 'c']
values = [1, 2, 3]
# Create the dictionary using the dict constructor and zip
result_dict = dict(zip(keys, values))
result_dict{'a': 1, 'b': 2, 'c': 3}
keys = ['a', 'b', 'c']
values = [1, 2, 3]
# Create the dictionary using a dictionary comprehension
result_dict = {key: value for key, value in zip(keys, values)}
result_dict{'a': 1, 'b': 2, 'c': 3}
from itertools import zip_longest
keys = ['a', 'b', 'c']
values = [1, 2]
# Create the dictionary using zip_longest to handle unequal lengths
result_dict = {key: value for key, value in zip_longest(keys, values)}
result_dict{'a': 1, 'b': 2, 'c': None}
a = [1, 2, 3]
c = list(a)
a == c
a is cFalse
Since the list function always creates a new Python list (i.e., a copy)
list1 = [1, 2, 3]
list2 = [4, 5, 6]+ Operatorcombined_list = list1 + list2
combined_list[1, 2, 3, 4, 5, 6]
extend() Methodlist1.extend(list2)
list1[1, 2, 3, 4, 5, 6]
* Operator (Python 3.5+)combined_list = [*list1, *list2, 7]
combined_list[1, 2, 3, 4, 5, 6, 4, 5, 6, 7]
combined_list = [item for sublist in (list1, list2) for item in sublist]
combined_list[1, 2, 3, 4, 5, 6, 4, 5, 6]
itertools.chain() Functionimport itertools
combined_list = list(itertools.chain(list1, list2))
combined_list[1, 2, 3, 4, 5, 6, 4, 5, 6]
Input: [["a"], ["b", "c"], ["d"]]
Desired output: ["a", "b", "c", "d"]
nested_list =[["a"], ["b", "c"], ["d"]]
flattened_list = [item for sublist in nested_list for item in sublist]
flattened_list['a', 'b', 'c', 'd']
itertools.chainThis is particularly useful for larger datasets:
import itertools
nested_list = [["a"], ["b", "c"], ["d"]]
flattened_list = list(itertools.chain(*nested_list))
flattened_list['a', 'b', 'c', 'd']
sum() with an Empty Listmay not be as efficient for very large lists:
nested_list = [["a"], ["b", "c"], ["d"]]
flattened_list = sum(nested_list, [])
flattened_list['a', 'b', 'c', 'd']
a = {'a', 'b', 'c' }
b = {'c', 'd'}
print(a | b)
print(a & b)
print(a - b)
print(a ^ b) # Symmetric difference {'c', 'b', 'd', 'a'}
{'c'}
{'b', 'a'}
{'b', 'd', 'a'}
a = [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][5, 4, 3, 2, 1]
firstfive = slice(0, 5)
s = 'hello world'
firstfiveslice(0, 5, None)
print(s[firstfive])hello