In Python, a "one-liner" is a concise and frequently ingenious solution to a problem that can be stated in only one line of code. For readability and maintainability in bigger codebases, they are not always advised, despite their sometimes-elegant and potent nature. They are, nevertheless, frequently employed in scripting, where conciseness is valued. Here are a few sample lines of code for one-liner solutions.
- Multiple variable assignments
name, age, occupation = "keisha", 30, "cook" print(name, age, occupation) # keisha 30 cook
- HTTP server
python -m http.server
- Swap variables
a = "a" b = "b" a, b = b, a print(a, b) # b a
- Ternary operator
yob = 1997 print("hey kid(gen alpha)" if yob >= 2013 else "wassup gen z" if yob >= 1995 else"hello millennials" if yob >= 1980 else "hey gen x" if yob >= 1965 else "hello baby boomer") # wassup gen z
- Variable unpacking
users = ['kalama', 'kairetu','munga','mwanaisha'] print(*users) #kalama kairetu munga mwanaisha user1, user2 , *other_users= users print(other_users) #['munga', 'mwanaisha']
- Reverse a list
z = [10,20,30,40] print(z[::-1]) #[40, 30, 20, 10]
- Sort a list
numbers = [1000000, -500000, 999999999, -1000000000, 123456789] print(sorted(numbers)) # [-1000000000, -500000, 1000000, 123456789, 999999999]
- Sort a list - reversed
numbers = [1000000, -500000, 999999999, -1000000000, 123456789] print(sorted(numbers, reverse=True)) #[999999999, 123456789, 1000000, -500000, -1000000000]
- Filter from a list
numbers = [1,2,3,4,5,6,7,8,9,10] odd = list(filter(lambda x: x%2!=0, numbers)) print(odd) #[1, 3, 5, 7, 9]
names = ['lizzy','bruce','wafula'] print([name.title() for name in names]) #['Lizzy', 'Bruce', 'Wafula']
- Remove duplicates from a list
num = [5, 2, 8, 3, 5, 2, 1, 8, 9, 4, 1] print(list(set(num))) # [1, 2, 3, 4, 5, 8, 9]
- Combine two lists to a dictionary
letters = ["a", "b", "c", "d"] num = [1,2,3,4] print(dict(zip(letters, num))) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
- Unpacking using * operator and zip
pair = [('jack', 50),('inaam', 80), ( 'Anna ', 70), ('John', 35)] names, marks = zip(*pair) print(names) print(marks) #('jack', 'inaam', 'Anna ', 'John') #(50, 80, 70, 35)
- Type conversion of items in an iterable using map function
strings = ("1","2","3","4","5","6","7","8") print(tuple(map(int, strings))) # (1, 2, 3, 4, 5, 6, 7, 8)
- Alternative value for input statements
username = input('Name: ') or 'N/A' #using ternary operator name_input = input('Name: ') username = name_input if name_input else 'N/A'
- Creating a shadow copy of a list
mylist = [1,2,3,4,5] copy_list = mylist[:]
Top comments (0)