Convert list into a list of 2-tuples - python

I have a list:
list = [1, 2, 3]
I want to get this list and add a tuple so this list becomes like this
T_list = [(1,x), (2, x), (3,x)]
How do I do it?

Use a simple list comprehension to do this:
>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples
Output
[(1, 100), (2, 100), (3, 100)]
Also, don't name your variables list, dict, etc, because they shadow the builtin types/functions.

A list comprehension would do the trick:
t_list = [(y,x) for y in original_list]
Also, the commenter is right. Don't name your lists list. It's a built in function. Using it for something else could cause problems down the line.

Here's my attempt, although I'm not an expert.
lis = [1,2,3]
tup = (4, 5, 6)
new_tup = tuple(lis)
new_lis = []
for i in range(0,3):
data = (new_tup[i],tup[i])
new_lis.append(data)
print(new_lis)

Related

Whats most pythonic way of colelcting second object of tuple in dictionary into a list

I have following objects
a = ("one", 1)
b = ("two", 2)
c = ("seven", 7)
my_dict = {10: a, 20:b, 70:c}
I want to get a list of [1, 2, 7] from my_dict. Whats the most pythonic way to do so?
Just use list comprehension. It's the most pythonic way of doing most things ;)
output = [x[1] for x in my_dict.values()]
If you like the functional way, you could use:
list(zip(*my_dict.values()))[1]
Output: (1, 2, 7)
Or, as list:
list(list(zip(*my_dict.values()))[1])
Output: [1, 2, 7]
You can use tuple unpacking inside the list comprehension to avoid having to index into the tuple:
result = [item for _, item in my_dict.values()]
print(result)
This prints:
[1, 2, 7]

return value: none -Python

I want to write a function that takes three lists of integers, l1, l2, and l3, and returns
a list of all tuples, where each tuple (a,b,c) is such that a is from l1, b is
from l2 and c is from l3 and a+b=c.
Expected Output:
[(2,5,7), (3,4,7), (3,5,8)]
The output I got:
None
Here is the code that I have written:
def threeList(l1, l2, l3):
result = []
for num in list3:
for x in list1:
for y in list2:
if x + y == num:
tuples = (x,y,num)
list_of_tuples = result.extend(tuples)
return list_of_tuples
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
threeList(list1, list2, list3)
Try this:
import itertools as it
list1 = [1,2,3]
list2 = [4,5]
list3 = [7,8]
[(x,y,x+y) for x,y in it.product(list1,list2) if x+y in list3]
which returns:
> [(2, 5, 7), (3, 4, 7), (3, 5, 8)]
itertools.product is a clean replacement for nested for loops.
extend is an in-place method which returns None.
Change your code to:
def threeList(l1, l2, l3):
result = []
for num in l3:
for x in l1:
for y in l2:
if x + y == num:
tuples = (x, y, num)
result.append(tuples)
return result
list1 = [1, 2, 3]
list2 = [4, 5]
list3 = [7, 8]
print(threeList(list1, list2, list3))
Output:
[(2, 5, 7), (3, 4, 7), (3, 5, 8)]
Explanation :
I used append instead of extend because we want the tuple tuples itself not the items inside it. Also I replaced the names list3, list1, list2 with l3, l1, l2 respectively because these are the actual values passed to the function, if your code works now is because list1, list2, list3 are exist in outside and those are referenced inside the function. Then after the loop finishes I return the result which is a list of tuples.
This was to fix your solution, but a better alternative solution is to use itertools modules like product in your situation.
Extend modifies the object itself. It does not return anything.
result.extend(tuples)
return result
Also note your code snippet is not working. So it is hard to spot your exact issue.
Did you make a typo?
Indentation wrong?
etc

List comprehension with tuple assignment

I want to ask if something like this is possible in python:
a,b = [i,i+1 for i in range(5)]
I know this isn't possible because I have got an error, but I think you understand what I am trying to achieve. Let me clear it up, I can do :
a,b = 3+2,3
Edit ---> Or even better:
a,b = [0,1,2,3,4],[1,2,3,4,5]
I wan't a similar thing in my first code example. I am trying to assign variables 'a' and 'b' as list, with list comprehension, but using tuple as assignment, the point is I don't want to use this:
a = [i for in range(5)]
b = [i+1 for in range(5)]
I am aware that I can use this: t = [(i,i+1) for i in range(5)], but that's not the point.
By the way this is only a simple example => "i,i+1"
Edit ---> I would like to clarify my question. How to assign several variables (type list) in one line, using list comprehension?
When you run this:
a,b = [(i,i+1) for i in range(5)] # wrapped i, i+1 in parentheses (syntax error)
It makes a list of five two-item tuples, like this:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
But you're trying to assign those five tuples to only two objects (a and b)
Using argument unpacking (*) in zip, you can "unzip" the output to the first and second elements of each tuple:
a,b = zip(*[(i,i+1) for i in range(5)])
Which is this:
[(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)]
And can be assigned to a and b as you've written
Don't try to be clever. This is perfectly acceptable code:
>>> a = range(5)
>>> b = range(1,6)
>>> a, b
([0, 1, 2, 3, 4], [1, 2, 3, 4, 5])

How To Merge an Arbitrary Number of Tuples in Python?

I have a list of tuples:
l=[(1,2,3),(4,5,6)]
The list can be of arbitrary length, as can the tuples. I'd like to convert this into a list or tuple of the elements, in the order they appear:
f=[1,2,3,4,5,6] # or (1,2,3,4,5,6)
If I know the at development time how many tuples I'll get back, I could just add them:
m = l[0] + l[1] # (1,2,3,4,5,6)
But since I don't know until runtime how many tuples I'll have, I can't do that. I feel like there's a way to use map to do this, but I can't figure it out. I can iterate over the tuples and add them to an accumulator, but that would create lots of intermediate tuples that would never be used. I could also iterate over the tuples, then the elements of the tuples, and append them to a list. This seems very inefficient. Maybe there's an even easier way that I'm totally glossing over. Any thoughts?
Chain them (only creates a generator instead of reserving extra memory):
>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain.from_iterable(l))
[1, 2, 3, 4, 5, 6]
l = [(1, 2), (3, 4), (5, 6)]
print sum(l, ()) # (1, 2, 3, 4, 5, 6)
reduce(tuple.__add__, [(1,2,3),(4,5,6)])
tuple(i for x in l for i in x) # (1, 2, 3, 4, 5, 6)
Use the pythonic generator style for all of the following:
b=[(1,2,3),(4,5,6)]
list = [ x for x in i for i in b ] #produces a list
gen = ( x for x in i for i in b ) #produces a generator
tup = tuple( x for x in i for i in b ) #produces a tuple
print list
>> [1, 2, 3, 4, 5, 6]
>>> from itertools import chain
>>> l = [(1,2,3),(4,5,6)]
>>> list(chain(*l))
[1, 2, 3, 4, 5, 6]
You can combine the values in a list using the .extend() function like this:
l = [(1,2,3), (4,5,6)]
m = []
for t in l:
m.extend(t)
or a shorter version using reduce:
l = [(1,2,3), (4,5,6)]
m = reduce(lambda x,y: x+list(y), l, [])

Sorting a list in Python using the result from sorting another list [duplicate]

This question already has answers here:
Sorting list based on values from another list
(20 answers)
Closed 8 years ago.
I have the two lists in Python
list_1 = [5, 2, 8];
list_2 = ['string1', 'string2', 'string3']
I would like to sort the fist list and use the result to sort the second list.
In other words, the result should be:
# Sorted in descending order
list_1_sorted = [8, 5, 2];
list_2_sorted = ['string3', 'string1', 'string2'];
I know how to sort each of these lists individually, but how I can permute one list using the permutation of indices resulting from sorting the other list?
Schwartzian transform
list_1_sorted, list_2_sorted = zip(*sorted(zip(list_1, list_2),
key=operator.itemgetter(0), reverse=True))
Zip the lists together, sort, unzip the lists:
together = zip(list_1, list_2)
sorted_together = sorted(together)
list_1_sorted = [x[0] for x in sorted_together]
list_2_sorted = [x[1] for x in sorted_together]
What's happening here is that zip creates a list of tuples, with the elements you want the list to be sorted by being the first elements:
>>> a = [1,3,7,3,2]
>>> b = ["one","two",'three','four','five']
>>> zip(a,b)
[(1, 'one'), (3, 'two'), (7, 'three'), (3, 'four'), (2, 'five')]
Then when you sort them, they elements stay paired:
>>> sorted(zip(a,b))
[(1, 'one'), (2, 'five'), (3, 'four'), (3, 'two'), (7, 'three')]
Then all that's left is to unpack these lists.
You can use zip:
>>> list_1 = ['string1', 'string2', 'string3']
>>> list_2 = [5, 2, 8]
>>> s = sorted(zip(list_2, list_1), reverse=True)
>>> list_1_sorted = [e[1] for e in s]
>>> list_2_sorted = [e[0] for e in s]
>>> list_1_sorted
['string3', 'string1', 'string2']
>>> list_2_sorted
[8, 5, 2]
>>>
#Ignacio's answer is the best, but just in case you need to sort the lists in-place without making new lists, you can try this:
import itertools
list_enumerate = itertools.count()
list_2.sort(reverse=True, key=lambda k: list_1[next(list_enumerate)])
list_1.sort(reverse=True)
print list_1
print list_2
Note that I do not think there is any guarantee that the key function is called for each list item in order (which is necessary for this to work), so this is a risky method to use.

Categories