2

I have a list

List = ['PK', 'K', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']

I have another list that has,

Grade = ['K','4','8']

I would like to see elements previous to 'K' and next to '8' from List and add it to Grade.

Expected result :

Grade = ['K','4','8','PK','9']
4
  • Why is PK at the beginning in the resulting list? Any reason? And can you detail what 'next' mean? You mean the following element? Commented Aug 26, 2019 at 8:15
  • 1
    Yes. PK stands for pre-kindergarden. Commented Aug 26, 2019 at 8:16
  • I mean does it have to go at the beginning in the resulting Grade list? Or can it go at the end? Commented Aug 26, 2019 at 8:16
  • It can go in the end as well. Please check the edited result. Commented Aug 26, 2019 at 8:18

4 Answers 4

2

this might work:

Grade = ['K','4','8']
Grade = Grade + [List[List.index(Grade[0]) - 1], List[List.index(Grade[-1]) + 1]]
# ['K', '4', '8', 'PK', '9']

get the index in your List and increase or decrease it by 1.

this will raise a ValueError if the first and last element of Grade are not in List.

Sign up to request clarification or add additional context in comments.

1 Comment

This works. Now if my Grade = ['PK','4','8'], the outcome is like, Grade= ['12', 'PK', '4', '8', '9']. Since PK is the first element in the list,I don't want to have '12' in my Grade to be included. Same applies for the last element.
0

Looks like you need.

lst = ['PK', 'K', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
Grade = ['K','4','8']
Grade = Grade + [lst[lst.index(Grade[0])-1], lst[lst.index(Grade[-1])+1]]
print(Grade) # --> ['K', '4', '8', 'PK', '9']

Comments

0

Grade.insert(Grade.index('8'), l[l.index('8')+1])

or this way for the previous item

Grade.insert(Grade.index('K'), l[l.index('K')-1])

it's best not to call your list "List", since that's an existing class in python

Comments

0
List = ['PK', 'K', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
Grade = ['K','4','8']
List[:List.index(Grade[0])]+ Grade + list(List[List.index(Grade[-1])+1])
#['PK', 'K', '4', '8', '9']

2 Comments

This works. Now if my Grade = ['PK','4','8'], the outcome is like, Grade= ['12', 'PK', '4', '8', '9']. Since PK is the first element in the list,I don't want to have '12' in my Grade to be included. Same applies for the last element.
@JenniferTherese the outcome would be ['PK', '4', '8', '9'] when Grade = ['PK','4','8']

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.