Skip to content
Advertisement

Tag: list

Combine two lists and sort them

Lets say I have two lists. I want to append list2 into list1 and then sort and add a new element at a specific index. I keep getting an error message saying: TypeError: ‘<‘ not supported between instances of ‘list’ and ‘int’ This is what I have tried: Answer Use sorted() if you want to print sorted list:

List comprehension returning two variables

I’m trying to do a list comprehension on two lists returning 2 variables in result. Using for loop: However, when I try to use list comprehension to do the same execution, it throws a SyntaxError Answer You need to have the whole thing in square brackets. Like this: That’s because you are doing the action in the first bit print(f,

Sorting list based on dictionary keys in python

Is there a short way to sort a list based on the order of another dictionary keys? suppose I have: I want to sort the list to be [‘a’,’b’,’c’] based on the order of dic keys. Answer You can create a lookup of keys versus their insertion order in dic. To do so you can write: Using this you can

Python – Generate permutations by key from key value pair list

Problem: I am generating a search query from key=value pairs. The system being queried does not support searching by the same field twice. I need to generate all unique permutations (assuming that is the correct word) of the pairs so I can generate multiple queries. Example query: python test.py –search field_1=”books” and (field_2=”paper” or (field_2=”abcd” and field_4=”test”)) and field_20=80 and

How to create new list of lists using for loop

I have two lists like I want to extract the required elements 1 and 3 from each list contained in values, to create a new list of lists like [[‘1234’, 50], [‘5678’, 100]]. I was able to solve the problem with a list comprehension: But how can I write the equivalent with explicit for loops? I tried: but the resulting

Check a list contains given elements

I want to check if my list’s first four elements are digits. what i did is as follows: But this gives the following error. How can I achieve this? Answer The error is telling you that you can’t do some_list in some_string – after all, a list consists of characters, not lists, so it’s pointless. You want to check if

Advertisement