Python Forum
(Fix it) Extend list with multiple other ones
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
(Fix it) Extend list with multiple other ones
#1
We need to be able to automatically extend our list with multiple other ones, here's an example:
How it works now:
sales_w1 = [7,3,42,19,15,35,9]
sales_w2 = [12,4,26,10,7,28]
sales = []
sales.extend(sales_w1)
sales.extend(sales_w2)
But could've been this:
sales_w1 = [7,3,42,19,15,35,9]
sales_w2 = [12,4,26,10,7,28]
sales = []
sales.extend(sales_w1, sales_w2)
How do I suggest the Python devs and contributors to get this function on board?
Thanks in advance!
Reply
#2
You can do
from itertools import chain

sales.extend(chain(sales_w1, sales_w2))
« We can solve any problem by introducing an extra level of indirection »
Reply
#3
Alternatively just unpack:

sales = [*sales_w1, *sales_w2]
Gribouillis likes this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
Wouldn't it be better to keep the weeks apart, so you can directly refer to any given week?

sales = {}
for i in range(1, 53):  
    # assume the poor staff must work 7 days a week, 52 weeks a year!  
    sales[f'sales_w{str(i)}'] = [randint(1, 50) for i in range(7)]  
How did we do in sales week 25?

print(sales['sales_w25'])
Output:
[39, 10, 7, 47, 17, 38, 12]
But if you really want all the sales together:

total_sales = []
for value in sales.values():
    total_sales = total_sales + value
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 3,090 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  View and extend native python class PythonDev 2 2,234 Oct-24-2020, 08:59 PM
Last Post: Gribouillis
  Multiple lambda functions in zipped list not executing psolar 0 2,037 Feb-13-2020, 12:53 PM
Last Post: psolar
  Why the this extend example is printing 2 two times? sbabu 1 2,127 Jan-12-2020, 07:30 AM
Last Post: Gribouillis
  How to combine file names into a list from multiple directories? python_newbie09 3 7,378 Jul-09-2019, 07:38 PM
Last Post: python_newbie09
  How to extend the sclale of a graph? Krszt 1 2,940 Nov-13-2018, 11:16 AM
Last Post: Larz60+
  Extend the scale Krszt 1 3,529 Nov-05-2018, 01:16 PM
Last Post: Gribouillis
  Balance integer list into multiple list of fixed value xenas 1 3,145 Oct-26-2018, 02:27 AM
Last Post: ichabod801
  generate filename of value and extend Marre 2 3,572 Oct-01-2018, 07:31 PM
Last Post: Larz60+
  changing characters in multiple strings in a list newmanf 3 3,728 Feb-23-2018, 06:23 PM
Last Post: newmanf

Forum Jump:

User Panel Messages

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