#๐Ÿ”’ Joining Lists: Hidden Downsides?

18 messages ยท Page 1 of 1 (latest)

lime gale
#

Beginner question ~

If I have three lists a and b and c what are the recommended ways for creating a new list with all of the elements of a, b and c?

It looks like there's a simple a + b + c ~ but then the internet gives me complicated-looking alternatives involving .extend() and from itertools import chain.

Is there some big non-obvious downside to x = a + b + c? It seems simple and clear code to me.

(Using Python 3.12.)

wary summitBOT
#

@lime gale

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

cinder gate
#

If you are just wanting to create a new list then the simple + approach is all you need. If you want to modify a list then extend is an option. The itertool solutions you've found would typically be for a scenario when it needs to support combining any number of lists

#

The only downside to + approach is when your lists are super large and it needs to be solved in a more memory efficient manner

woven monolith
#

The itertools method specifically is nice when your lists are big and you donโ€™t instantly need all the elements. Iterators are lazy, so they only get the data as needed. This can be very worthwhile if you are joining big lists, but only need a small portion at a time.

rain fiber
#

chaining adds also re-allocates each time

#

if you actually need a list as output, and not an iterator, then I suggest this syntax

joined = [*a, *b, *c]
lime gale
#

I appreciate the answers. I'm just a beginner doing small things, so it sounds like + works fine. I've made notes for the other explanations. Thank you. ๐Ÿ˜ธ

urban stream
#

!e py a = [1, 2, 3] b = [a, a, a] print(b) a[0] = 0 print(b)

wary summitBOT
urban stream
#

!e py a = [[1, 2, 3]] b = [[4, 5, 6]] c = [[7, 8, 9]] d = a + b + c print(d) b[0][:] = 0, 0, 0 print(d)Beware of lists with references to mutables.

wary summitBOT
urban stream
#

Concatenating and extending lists that only have references to immutables is often fine.

#

Lists of ints/strings, etc.

#

Lists of sets, lists, dictionaries, immutables that in turn have mutables...that's where you can run into trouble.

#

This is more a caveat of working with lists in general, rather than joining them.

wary summitBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.