Py_Student
Py_Student

Reputation: 159

How to explicitly choose elements from a list

my_list = ["zero", "wow", "peach", 3, 4, "nice", "pickle"]

I want to print "wow", "nice", "peach"

So:

my_list[1]
my_list[5]
my_list[2]

How can I do this in one line, or at-least quicker than the above?

Upvotes: 0

Views: 113

Answers (5)

Jaysmito Mukherjee
Jaysmito Mukherjee

Reputation: 1526

If anyone like a simple way without any library of complex looking syntax this might be a solution!

To make code look clean the best way is to have a function for it it makes it both more clean and also has more features.

Code :

def printList(list, *index, all=False):
    if all:
        for item in list:
            print(item)
    else:
        for i in index:
            print(list[i])

my_list = ["zero", "wow", "peach", 3, 4, "nice", "pickle"]

printList(my_list, 1, 5, 2) # To print some elements
print("---------------------------")
printList(my_list, all=True)

Output :

wow
nice
peach
---------------------------
zero
wow
peach
3
4
nice
pickle

Upvotes: 1

Jack Campbell
Jack Campbell

Reputation: 154

You can also use list comprehension

>>> [my_list[x] for x in [1, 5, 2]]
['wow', 'nice', 'peach']

or even

>>> [print(my_list[x]) for x in [1, 5, 2]]
wow
nice
peach

Upvotes: 1

Nick
Nick

Reputation: 147236

You can use a list comprehension to return a list of values:

[my_list[i] for i in [1, 5, 2]]

Or to print one by one:

for i in [1, 5, 2]:
    print(my_list[i])

or as a 1-liner using the argument unpacking (*) operator to "flatten" a generator:

print(*(my_list[i] for i in [1, 5, 2]), sep='\n')

Upvotes: 3

Amit Vikram Singh
Amit Vikram Singh

Reputation: 2128

Use:

print(*map(lambda x: my_list[x], [1, 5, 2]))

Output:

 wow nice peach

Upvotes: 1

python_user
python_user

Reputation: 7123

You can use operator.itemgetter

>>> from operator import itemgetter
>>> my_list = ["zero", "wow", "peach", 3, 4, "nice", "pickle"]
>>> itemgetter(1, 5, 2)(my_list)
('wow', 'nice', 'peach')

Upvotes: 4

Related Questions