Python Forum
short way to combine tuples and int's
Thread Rating:
  • 3 Vote(s) - 2.33 Average
  • 1
  • 2
  • 3
  • 4
  • 5
short way to combine tuples and int's
#1
if I have four kinds of data like
l1 = 1   #int
l0 = 8   #int
l2 = 2,3 #tuple
l3 = 4,5 #tuple
Is there an elegant single method to combine any two of these data and return a flattened tuple


for example if a method takes in m = l1,l3
it returns (1,4,5)
note that assuming I don't know the data type of elements in m when using this method
maybe there is a special method I can use but I don't know it
Reply
#2
* and ** specifiers in the function’s parameter.
This gives you the positional arguments as a tuple and the keyword arguments as a dictionary.
def foo(*args):
   return args

>>> l0 = 8 
>>> l1 = 1 
>>> l2 = 2,3
>>> l3 = 4,5

>>> foo(l1, l3)
(1, (4, 5))
>>> foo(l0, l1, l2, l3)
(8, 1, (2, 3), (4, 5))
Reply
#3
Thank you!

But what if I want (4,5) to be unpacked in the result ?

so (1,4,5) instead of (1,(4,5))
Reply
#4
Why does it need to be short? Why not just use an if statement?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Hmm...
Would one if statement be enough? there are three possibilities and they all need different treatment to get the desired result, right ? I mean something like (1,2,3,4,5)

Just asking if there are shorter ways to do this, if not, I'll use the if statement then
Reply
#6
Is it possible to start with all tuples, for example

>>> a = 1,
>>> b = (2, 3)
>>> c = a + b
>>> c
(1, 2, 3)
>>>
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#7
Thanks!
Yeah, that is what I'm thinking, I guess I can try to find the int element in m, convert it to a tuple in m, then flatten the multi dimensional tuple
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Short code for EventGhost not working Patricia 8 3,666 Feb-09-2021, 07:49 PM
Last Post: Patricia
  How can I make a short-key in Spyder (Python IDE)? moose 3 2,673 Nov-02-2020, 12:13 PM
Last Post: jefsummers
  Short font question Pizzas391 9 3,270 Nov-27-2019, 05:57 PM
Last Post: ichabod801
  float.hex() is one bit short Skaperen 4 4,099 Jul-26-2017, 03:53 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020