11

I remember I once seen a operator which is able to decompose a list in python.

for example

[[1],[2],[3]]

by applying that operator, you get

[1], [2], [3]

what is that operator, any help will be appreciated.

Trufa
  • 39,971
  • 43
  • 126
  • 190
Jerry Gao
  • 1,389
  • 3
  • 13
  • 17

4 Answers4

19

If you want to pass a list of arguments to a function, you can use *, the splat operator. Here's how it works:

list = [1, 2, 3]
function_that_takes_3_arguments(*list)

If you want to assign the contents of a list to a variable, you can list unpacking:

a, b, c = list # a=1, b=2, c=3
Evan Kroske
  • 4,506
  • 12
  • 40
  • 59
  • 1
    I guess the `*` is the operator in question. It works only in function calls! – Jochen Ritzel Jun 12 '11 at 02:14
  • ah, finally, I was trying *, but now know it works only in function calls, thanks for the help guys. – Jerry Gao Jun 12 '11 at 12:20
  • NB: If the list is shorter than expected params, it will throw eg. ``TypeError: func() missing 1 required positional argument: 'c'``, unless the function uses a default value for all parameters. In that case, it fills them in order, and the items beyond list length use the default value. – Juha Untinen Sep 25 '18 at 07:14
2

You can use the tuple function to convert a list to a tuple. A tuple with three elements isn't really any different from three separate elements, but it gives a handy way to work with all three together.

li = [[1], [2], [3]]
a, b, c = tuple(li)
print a  # [1]
RoundTower
  • 899
  • 5
  • 9
  • 4
    Adding `tuple` is pretty pointless because `a, b, c = li` works just the same. – Jochen Ritzel Jun 12 '11 at 02:12
  • It's pointless in this example but if you don't unpack it straight away, it's not. You can do some things with tuples you can't do with lists: in particular, use them as dictionary keys. – RoundTower Jun 12 '11 at 10:48
1

The correct answer to the OP's question: "what is that operator" which transforms the list [[1],[2],[3]] to [1], [2], [3] is tuple() since [1], [2], [3] is a tuple. The builtin function tuple will convert any sequence or iterable to a tuple, although there is seldom a need to do so since, as already pointed out, unpacking a list is as easy as unpacking a tuple:

a, b, c = [[1],[2],[3]]

gives the same result as

a, b, c = tuple([[1],[2],[3]])

This may not be what the OP wanted but it is the correct answer to the question as asked.

Don O'Donnell
  • 4,538
  • 3
  • 26
  • 27
0

This can be achieved by running sum(list_name,[]) as mentioned here.

You may also find this question on flattening shallow lists relevant.

Community
  • 1
  • 1
wting
  • 900
  • 2
  • 13
  • 27