0

I cant get my head around how to do this. I have a nested list, which I want to use as function arguments.

The function.

pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, {commands} ])

I would like to loop through the list so the end result is like below.

NestedList = [[1,2,3,4,5,6,7,8],[2,0,2,0,2,0],[0,0,1,1,0,0]]

pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, 1,2,3,4,5,6,7,8 ])
pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, 2,0,2,0,2,0 ])
pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, 0,0,1,1,0,0 ])

If i try using this;

for i in NestedList:
  pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, i ])

I get this errror; TypeError: an integer or string of size 1 is required

This is because the function is expecting bytes and the loop above is placing in an actual list of bytes.. E.g. pi.bb_i2c_zip(SDA, [4, address, 2, 7,18,[1,2,3,4,5,6,7,8]])

in summary, how can I place; 1,2,3,4,5,6,7,8 into the function and not this [1,2,3,4,5,6,7,8]

1
  • pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, *i ]) Commented Jul 8, 2021 at 14:55

1 Answer 1

4

You have to unpack the list first.

for i in NestedList:
  pi.bb_i2c_zip(SDA, [4, address, 2, 7,18, *i ])

Otherwise, your list argument is just another nested list. The * unpacking is more efficient (though possibly less clear) than [4, address, 2, 7, 18] + i. Unpacking also works with any iterable i, whereas + requires conversion of i to a list (i.e., [...] + list(i)).

Sign up to request clarification or add additional context in comments.

2 Comments

"The * unpacking is more efficient (though possibly less clear)" Personally looks clear to me. I would probably just rename i to something more meaningful.
I very much like [..., *i], but I don't think it's obvious at first glance that prefixing a * will expand the iterable to its elements. It's certainly a good idiom once you adjust to it, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.