How to append values at specific indices from one list to another list in a for loop?

Question:

I want to append my_list

list2 = ['1','2','3','4','5']

my_list = []
for i in list2:
    my_list.append(i)

print(my_list)

This will put the list2 to my_list.

The result is

['1', '2', '3', '4', '5']

but i want only the value ‘2’ and ‘5’ )

So something like this:

[ '2', '5']

Have tried

for i in list2:
    my_list.append(i[1:4])

Any Idea?

Asked By: Drik Drik

||

Answers:

Just use one condition in combination with list comprehension:

my_list = [item for item in list2 if item == '2' or item == '5']

It depends how are deciding what elements of list2 should be added to my_list, which you have not mentioned:
Right now you can do what @MihaiAlexandru-Ionut suggested.
or:

list2 = ['1','2','3','4','5']

my_list = []
my_list.append(list2[1])
my_list.append(list2[4])

print(my_list)

# or

my_list = []
my_list = [list2[1], list2[4], ]
print(my_list)
Answered By: Vaibhav Vishal

Here’s a short way of doing it. But beware though it will break if there are repeating elements in the list.

list2 = ['1','2','3','4','5']

my_list = []

want = ['2', '5']

my_list = [list2[list2.index(i)] for i in list2 for item in want if i == item] # will fail if elements are not unique.

the last line is equivalent to this

my_list = [item for i in list2 for item in want if i == item] # much better than using index method.

And here’s the expanded form.

list2 = ['1','2','3','4','5']
my_list = []
want = ['2', '5']
for i in list2:
    for item in want:
        if i == item:
            my_list.append(list2[list2.index(i)])
            #my_list.append(item)


print(my_list)
Answered By: Vineeth Sai

May be like that

list2 = ['1','2','3','4','5']

target_idexes = [2, 5]

my_list = []
for i in list2:
    my_list.append(i) if int(i) in target_idexes else 0

print(my_list)    # ['2', '5']

or if in list2 not only digits:

list2 = ['1','2','3','4','5']

target_idexes = [2, 5]

my_list = []
for i in list2:
    my_list.append(i) if list2.index(i) in target_idexes else 0

print(my_list)    # ['3'] because indexing start from 0 and 5 is out of range
Answered By: Andrey Topoleov

The easiest and fastest way is to use an conditional statement for the specific value that you are searching inside the loop.

if i == 2 or i == 5:
   new_list.append(i)

The drawback of this approach is, that if you need to expand the range of values that you want retrieve you will need to write a longest condition if i == 1 or i == 5 ... or i == N: , that’s not only bad to see but a bad programming practice because the code is hard to mantain.

A better way is to have a list with the values that you want retrieve and check if the actual element is this list before adding it to the new list.

list2 = ['1','2','3','4','5']

wanted = ['2','5'] #what I search
my_list = []
for value in list2:
  if value in wanted: #when value is what a I want, append it
    my_list.append(value)

However if you want to add the elements by their position, not to find every occurrences of a specific value, you can use a list of integers and loop over it to add the wanted elements.

positions = [1,4] #indicates the positions from which I want to retrieve elements
new_list = [list[p] for p in positions] #using list comprehension for brevity

Note

Last thing that I would like to add is that in python you can’t execute

my_list.append(i[0,4]) 

because python when looks at [0,4], will interpret it like you are passing a tuple (because of the comma) and will rise the following error TypeError: list indices must be integers or slices, not tuple.

Answered By: Iulian
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.