PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How do I append to list only after a certain value in another python list?

 May 13, 2022     append, python     No comments   

Issue

I have 2 lists. I only want to append to the new list after I've reached the specified value.

old_list = ['apple', 'pear','orange', 'banana', 'grape']
new_list = []
value  = 'orange'

The desired outcome is:

new_list = ['banana', 'grape']

I've tried this, but the result is not what I want:

for i in old_list:
    if i != value:
        new_list.append(i)

Hope that makes sense!


Solution

Use the list.index method to return the index i where the value appears in the old_list. Then slice old_list from index i+1 up to its end:

old_list = ['apple', 'pear','orange', 'banana', 'grape']
value  = 'orange'

i = old_list.index(value)
new_list = old_list[i+1:]


Answered By - jfaccioni
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing