Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the first x item from a list [duplicate]

Tags:

python

Possible Duplicate:
Good Primer for Python Slice Notation

I have a string and I'm splitting in a ; character, I would like to associate this string with variables, but for me just the first x strings is useful, the other is redundant;

I wanted to use this code below, but if there is more than 4 coma than this raise an exception. Is there any simply way?

az1, el1, az2, el2, rfsspe = data_point.split(";")  
like image 502
Kicsi Mano Avatar asked Feb 06 '12 17:02

Kicsi Mano


People also ask

How do you check if a number is repeated in a list Python?

Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count().

How do I remove the first duplicate element from a list in Python?

Method 1: Using *set() It first removes the duplicates and returns a dictionary which has to be converted to list.


2 Answers

The way, I do this is usually to add all the variables to a list(var_list) and then when I'm processsing the list I do something like

for x in var_list[:5]:
    print x #or do something
like image 43
Lostsoul Avatar answered Oct 25 '22 03:10

Lostsoul


Yes! Use slicing:

az1, el1, az2, el2, rfsspe = data_point.split(";")[:5]

That "slices" the list to get the first 5 elements only.

like image 66
Cameron Avatar answered Oct 25 '22 03:10

Cameron