Python
[Basic Grammar] Python Arrays
grace21110
2023. 10. 21. 18:38
반응형
- Array
3
An array is a special variable, which can hold more than one value at a time.
- Access the elements of an array
Refer to the index number.
Example
colors = ["white", "blue", "red"]
x = colors[0]
print (x)
white
Change the value of third array item.
colors = ["white", "blue", "red"]
colors[2] = "black"
print (colors)
['white', 'blue', 'black']
- The length of an array
Use len () to get a result of length of an array.
Example
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
3
- Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
colors = ["white", "blue", "red"]
for x in colors:
print (x)
- Adding Array Elements
Use append() to add an element to an array.
Example
colors.append ("purple")
- Removing Array Elements
There are two different ways you can remove the elements in an array.
- pop()
Example
Remove the second element in the array.
colors.pop(1)
- remove()
Example
Remove the value white.
colors.remove("white")
Exercises
1. Create a Python program that takes a list of names and counts how many names in the list start with the letter "A."
names = ["Alice", "Bob", "Charlie", "David", "Anna", "Eva"]
count_a_name = len ([name for name in names if name.startswith("A")])
print ("Number of names starting with 'A':", count_a_names)
Number of names starting with 'A': 2
2. Get the value of the first array item.
names = ["Alice", "Bob", "Charlie", "David", "Anna", "Eva"]
x = names[0]
print(x)
Alice