Bob Kim
Bob Kim

Reputation: 61

Slicing large lists based on input

If I have multiple lists such that

hello = [1,3,5,7,9,11,13]

bye = [2,4,6,8,10,12,14]

and the user inputs 3

is there a way to get the output to go back 3 indexes in the list and start there to get:

9 10

11 12 

13 14

with tabs \t between each space.

if the user would input 5

the expected output would be

5 6

7 8

9 10

11 12

13 14

I've tried

for i in range(user_input):
    print(hello[-i-1], '\t', bye[-i-1])

Upvotes: 4

Views: 513

Answers (6)

Carson
Carson

Reputation: 8008

If you want to analyze the data

I think using pandas.datafrme may be helpful.

INPUT_INDEX = int(input('index='))

df = pd.DataFrame([hello, bye])
df = df.iloc[:, len(df.columns)-INPUT_INDEX:]
for col in df.columns:
    h_value, b_value = df[col].values
    print(h_value, b_value)

console

index=3
9 10
11 12
13 14

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155418

Another zip solution, but one-lined:

for h, b in zip(hello[-user_input:], bye[-user_input:]):
    print(h, b, sep='\t')

Avoids converting the result of zip to a list, so the only temporaries are the slices of hello and bye. While iterating by index can avoid those temporaries, in practice it's almost always cleaner and faster to do the slice and iterate the values, as repeated indexing is both unpythonic and surprisingly slow in CPython.

Upvotes: 1

Liaoleilei
Liaoleilei

Reputation: 1

You can use zip to return a lists of tuple where the i-th element comes from the i-th iterable argument.

zip_ = list(zip(hello, bye))
for item in zip_[-user_input:]:
    print(item[0], '\t' ,item[1])

then use negative index to get what you want.

Upvotes: 0

blhsing
blhsing

Reputation: 106588

You can zip the two lists and use itertools.islice to obtain the desired portion of the output:

from itertools import islice
print('\n'.join(map(' '.join, islice(zip(map(str, hello), map(str, bye)), len(hello) - int(input()), len(hello)))))

Given an input of 3, this outputs:

5 6
7 8
9 10
11 12
13 14

Upvotes: 0

Dave
Dave

Reputation: 622

Use negative indexing in the slice.

hello = [1,3,5,7,9,11,13]

print(hello[-3:])

print(hello[-3:-2])

output

[9, 11, 13]
[9]

Upvotes: 0

Paul Evans
Paul Evans

Reputation: 27577

Just use negative indexies that start from the end minus the user input (-user_input) and move to the the end (-1), something like:

for i in range(-user_input, 0):
    print(hello[i], bye[i])

Upvotes: 4

Related Questions