Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add tuple to list of tuples in Python

Tags:

python

tuples

I am new to python and don't know the best way to do this.

I have a list of tuples which represent points and another list which represents offsets. I need a set of all the combinations that this forms. Here's some code:

offsets = [( 0, 0),( 0,-1),( 0, 1),( 1, 0),(-1, 0)]
points = [( 1, 5),( 3, 3),( 8, 7)]

So my set of combined points should be

[( 1, 5),( 1, 4),( 1, 6),( 2, 5),( 0, 5),
 ( 3, 3),( 3, 2),( 3, 4),( 4, 3),( 2, 3),
 ( 8, 7),( 8, 6),( 8, 8),( 9, 7),( 7, 7)]

I'm not able to use NumPy or any other libraries.

like image 717
rlbond Avatar asked Dec 10 '09 03:12

rlbond


People also ask

Can we add tuple to list in Python?

In Python, we can easily add a tuple to a list with the list extend() function. You can also use the += operator to append the items of a tuple to a list in Python. When working with collections of data in Python, the ability to add and remove elements from an object easily is very valuable.

How do I add a tuple to another tuple?

Add/insert items to tuple If you want to add new items at the beginning or the end to tuple , you can concatenate it with the + operator as described above, but if you want to insert a new item at any position, you need to convert a tuple to a list. Convert tuple to list with list() . Insert an item with insert() .

Can you make a tuple of tuples in Python?

Creating a TupleA tuple in Python can be created by enclosing all the comma-separated elements inside the parenthesis (). Elements of the tuple are immutable and ordered. It allows duplicate values and can have any number of elements. You can even create an empty tuple.


1 Answers

result = [(x+dx, y+dy) for x,y in points for dx,dy in offsets]

For more, see list comprehensions.

like image 67
Alok Singhal Avatar answered Sep 29 '22 06:09

Alok Singhal