About Python Lists

About Python Lists

Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name

..You can assign items to a list with

Example :

$ list_name = [item_1, item_2]

Example :

A list can also be empty:

$ empty_list = []

Example :

$ animals = ["cat", "dog", "lion", "tiger"];
 
print "The first " + animals[0]
print "The second " + animals[1]
print "The third " + animals[2]
print "The fourth " + animals[3]

Example :

$ numbers = [5, 6, 7, 8]

$ print numbers[0] + numbers[2]

$ 12

Replace list value

$ animals[2] = "zzz"

..You can add items to the end of a list

$ number.append(“9”)


..List Slicing

Sometimes, you only want to access a portion of a list.

number[:2]

#Grabs the first two items

number[3:]

#Grabs the fourth through last items
$ number[2:5]

# Grabs the 3 to 4 items


.List Length

$ len(number)

......you need to search for an item in a list.

$ animals= ["ant", "bat", "cat"]

$ print animals.index("bat")
.......We can also insert items into a list.

$ animals.insert(1, "dog")

$ print animals
.If your list is a jumbled mess, you may need to sort() it.

$ animals = ["cat", "ant", "bat"]
$ animals.sort()

for animal in animals:
       print
     animal
examle 2

start_list = [5, 3, 1, 2, 4]

square_list = []

# Your code here!
for x in start_list:
           square_list.append(x**2)
square_list.sort()
print square_list

Comments

Popular posts from this blog

AttributeError: Got AttributeError when attempting to get a value for field `abc` on serializer `PfleSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'abc'.

ImportError: No module named regex