Last active
January 20, 2020 20:00
-
-
Save karpanGit/8dc29b2280bf1c00efde42d377f9ca13 to your computer and use it in GitHub Desktop.
* and ** operators in python (star, double star operators)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# * and ** operators in python | |
data1 = [1,2,3] | |
print(data1) | |
print(*data1) | |
''' | |
[1, 2, 3] | |
1 2 3 | |
''' | |
# join two lists | |
data2 = ['a', 'b', 'c'] | |
res = [*data1, *data2] | |
print(res) | |
''' | |
[1, 2, 3, 'a', 'b', 'c'] | |
''' | |
# join a list and a tuple | |
data3 = ('a', 'b', 'c') | |
res = [*data1, *data3] | |
print(res) | |
''' | |
[1, 2, 3, 'a', 'b', 'c'] | |
''' | |
# create list from string | |
res = [*'hello'] | |
print(res) | |
''' | |
['h', 'e', 'l', 'l', 'o'] | |
''' | |
res = list('hello') | |
print(res) | |
''' | |
['h', 'e', 'l', 'l', 'o'] | |
''' | |
# join two dicts | |
data4 = {'a1':10, 'b1':11, 'c1':12} | |
data5 = {'a2':20, 'b2':21, 'c2':22} | |
res = {**data4, **data5} | |
print(res) | |
''' | |
{'a1': 10, 'b1': 11, 'c1': 12, 'a2': 20, 'b2': 21, 'c2': 22} | |
''' | |
# using asterisk operator in assignment operators | |
x, *y = data1 | |
print(y) | |
''' | |
[2, 3] | |
''' | |
x, y, *z = data1 | |
print(z) | |
''' | |
[3] | |
''' | |
x, *y, z = data1 + data2 | |
print(y) | |
''' | |
[2, 3, 'a', 'b'] | |
''' | |
# a very esoteric example (comma is required because a star assignment should be in a list or tuple) | |
*y, = data1 | |
print(y) | |
''' | |
[1, 2, 3] | |
''' | |
# an even more esoteric example | |
[*y] = data1 | |
print(y) | |
''' | |
[1, 2, 3] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment