Home > Software engineering >  Python - How to make a list using existing elements
Python - How to make a list using existing elements

Time:10-12

I'm looking for a simple line of code which would let me create a list made of elements from other lists. Example: new_list = [list1[2:5], list2[3]] The problem with the line of code above is that the list that is created looks like this [[X, Y, Z], Y], while I need it to look like this [X, Y, Z].

To clarify, the indexes of the items of the lists we are taking from (in this example, [2:5] and [3]) would ideally be any number, like [10:1156:3], [-2]. For this reason I exclude using new_list = [list1[2], list1[3], list1[4], list2[3].

CodePudding user response:

List slicing returns a new list. You can "unpack" the slice:

new_list = [*list1[2:5], list2[3]]

Or you can add lists, which concatenates them:

new_list = list1[2:5]   [list2[3]]
  • Related