2

I have the following list:

my_list = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"]

But how do I access multiple elements in this list?

I know how to access one specific element (e.g., my_list[1] gives me [1.2]) and a range (e.g., my_list[1:3] gives me [1.2, 1]) but how do I get the first and third to last element?

["shanya", 1, False, "test", 2, 3.3, True, "3", "4.0"]
1
  • Index 1 will give you the second item. If you want the first item you need to use 0. Commented Sep 22, 2018 at 8:59

2 Answers 2

2

You can use itemgetter:

>>> from operator import itemgetter

>>> values = ["shanya", 1.2, 1, False, "test", 2, 3.3, True, "3", "4.0"]

>>> itemgetter(0, -3)(values)
('shanya', True)
Sign up to request clarification or add additional context in comments.

Comments

0

Simply contact the sub-lists, like:

result = l[:1] + l[2:]

output:

['shanya', 1, False, 'test', 2, 3.3, True, '3', '4.0']

2 Comments

ok I have to use the "range" (a to b) instead of specifying one element [a]. Otherwise I get an error TypeError: can only concatenate list (not "float") to list
@rororo sounds like your "float" is not in a list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.